Event Handlers is one of the most important features of JavaScript.
I came across a situation where I need to attach even to controls dynamically
using JavaScript. So Event Handler helped me to finish of the task. Different methods can be invoked from the same
event handler and we can remove it whenever it is not necessary.
Types of Event Handlers as follows,
The addEventListener() Method
It actually allow you to specify a function to be executed for
the event
Syntax:
element.addEventListener('event_type', function_name, true_or_false);
Sample Eg:
var mypage= "http://www.ajaal.com";
var varCtrl = document.getElementById("btnRedirect");
varCtrl.addEventListener('click', function() { window.location =
mypage;
}, false);
The removeEventListener() Method
To remove an event whenever we don’t need we can use the
removeEventListener() method.
Syntax:
element.removeEventListener('event_type', function_name,
true_or_false);
The attachEvent() Method
The attachEvent() method works in a similar way to
addEventListener(). However, it only
works with event bubbling.
Syntax
element.attachEvent(event_handler, function_name);
Sample Eg:
var mypage = " http://www.ajaal.com ";
var varCtrl = document.getElementById("btnRedirect");
varCtrl.attachEvent(onclick, function() { window.location = mypage;
} );
Notice that this method does use the name of the event handler
(onclick). Also, it does not
have the third option; it just uses event bubbling.
The detachEvent() Method
To remove an event, you would use the detachEvent() method:
Syntax
element.detachEvent(event_handler, function_name)
Please comment your suggestion on this post for further improvement.