Lecture 4: HTML Events, The Event Object, Error Handling, Try, Throw, Exception, Catch, Custom Exception, Detour - Regular Expression, XML Http Request
HTML Events
- Something browser or user does. Eg. change input, click button or any element, page loaded
- HTML allows JavaScript Event Handler attributes to be added to the HTML elements.
-onchange onclick onmouseover onmouseout onkeydown onload Make a note of all http://www.w3schools.com/jsref/dom_obj_e…
Add Event Handlers
- JavaScript code or function call in an attribute<some-HTML-element some-event='some JavaScript'>
<button onclick="this.innerHTML='New Text'">Old Text</button>
<input onchange='alert("new")' value="Hello"/>- The addEventListener() method Syntax : element.addEventListener(event, function, useCapture);
addEventListener("click", function(){
alert("You clicked");
});//adds event listener to global scope (the window object)
useCapture is an optional argument. It is a Boolean value.
window.addEventListener("click",function(){alert(1)},false);
window.addEventListener("click",function(){alert(2)},true);
window.addEventListener("click",function(){alert(3)},false);
window.addEventListener("click",function(){alert(4)},true);- Add event listener to an HTML element
<button>Click me</button>
<p>No Handler here</ p>
<script>
var btn= document.querySelector("button");
btn.addEventListener("click", function(){
alert("Button clicked");
}) ;
</script>
- QuerySelector syntax
document.querySelector(CSS selectors)
More methods of document at http://www.w3schools.com/jsref/dom_obj_d…
More about CSS selectors at http://www.w3schools.com/cssref/css_sele…- Multiple event handlers can be used on an element using addEventListener method
Event Propagation : Beware of it!
<html><body style="height: 800px; width: 800px">
<p>This is a pragraph. This is paragraph.<button>I am inside paragraph.</button> This paragraph continued</p></body>
<script>
document.querySelector("p").addEventListener("click", function(){alert("para clicked")});
document.querySelector("button").addEventListener("click", function(){alert("button clicked")});
document.querySelector("p").addEventListener("mouseout", function(){alert("Pointer out of para")});
document.querySelector("button").addEventListener("mouseout", function(){alert("Pointer out of button")});
</script></html>Remove an Event Handler
- removeEventListener() method<button>Only once</button>
<script>
var btn = document.querySelector("button");
function once(){
alert("I will appear only once");
btn.removeEventListener("click",once);
}
btn.addEventListener("click",once);
</script>The Event Object
<button>Click any mouse button on me</button>
<script>
var btn= document.querySelector("button");
btn.addEventListener("mousedown", function(event){
if(event.which==1)
alert("Left Button");
else if(event.which==2)
alert("Middle button");
else if(event.which==3)
alert("Right Button");
});
</script>
-Use Event object's method to stop Event propagation
event.stopPropagation();
- Exercise time Make a program which draws dots at the point where pointer is when the mouse is clicked or dragged.
Error Handling
- Strict Mode"use strict";
function Person(name)
{this.name=name;}
var person1= Person("Shirish"); //gives an error
function strictFunction(){
"use strict";
for(counter=0; counter<10; counter++)
console.log(counter);
}
"use strict";
var o = { p: 1, p: 2 }; //syntax errorTry, Throw, Exception, Catch
try {
var dir = promt (" Where ?") ; //typo here
console.log ("You entered " , dir ) ;
} catch (e) {
console.log (e) ;
}
try{
var num = prompt("Enter a number");
if(isNaN(num)){
throw new Error("Not a Number "+num);
}else
console.log("num is "+num);
}catch(ecp){
console.log(ecp.message);
}Custom Exception
function myException(message){
this.message = message;
this.name = "CustomException";}
function getDayName(da){
da = da-1;
var days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
if (days[da] !== undefined) {return days[da];}
else {throw new myException("Invalid Day number");}
}
try {
var myDay = 8; //8 should raise the exception
dayName = getDayName(myDay);
} catch(e){
if(e instanceof myException)
console.log(e.message, e.name);
else
console.log(e);
}Detour - Regular Expression
var aRegExp = new RegExp("abc");
var otherRegExp = /abc/; //sequence of characters between / & /
otherRegExp.test("abcde"); //true
otherRegExp.test("abfde"); //false
// use \ if you want to include the / or special chars
/[abc]/.test("alb"); // []=Any char from a set of chars
/[^abc]/.test("ayg");//^ inside [] means any char not in the set
/[0-9]/.exec("a6b");// - inside [] means range of chars
/a+/.exec("aabaa");// + means 1 or more occurrences of the char
/x*/.test("abc");// * means Zero or more occurrences
/ax?/.test("xxxa");// x optional after a
/a{2,4}/.exec("aba");// {} denotes range, 2 to 4 occurrences/(abc)/ // () makes the sequence inside it a group
/ay|b|c/.exec("axay");// | Any one of several patterns
/\d/.test("k88k");// \d means any digit character
/\w/.test("a.bc");// \w means alphanumeric char
/\s/.test("a n \n");// \s means any whitespace char
/./.test("a n");// . means any character except newlines
/th\b/.test("Kath");// \b means a word boundary
/^a/.test("Kath");// ^ means start of input
/(ing)$/.test("eating");// $ means end of input
^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$XML Http Request
- Synchronous requestmyXHR=new XMLHttpRequest(); myXHR.open("GET","http://www.w3schools.com/dom/xmlhttp_inf…); myXHR.send(); alert(myXHR.responseText); alert("Synchronous");- Asynchronous request
myXHR=new XMLHttpRequest();
myXHR.onreadystatechange=function(){
if (myXHR.readyState==4 && myXHR.status==200)
alert(myXHR.responseText);
}
myXHR.open("GET","http://www.w3schools.com/dom/xmlhttp_inf…);
myXHR.send();
alert("Asynchronous");XML Http Request
Post Method<form method="post" action="somewhere"
onsubmit="submitForm(this);">
<input type="text" name="user" />
<input type="text" name="pwd" />
<input type="submit" value="Send"/>
</form>
<script>
function submitForm(formObj){
var myxhr = new XMLHttpRequest();
myxhr.onload = function(){ alert (myxhr.responseText); }
myxhr.open (formObj.method, formObj.action, true);
myxhr.send (new FormData (formObj));
}
</script>