As an alternative to Event handlers, JavaScript has event listeners. This alternative mainly addresses the problem that you cannot have multiple event handlers for the same event on the same element.
Consider the following code snippet
var btn = document.querySelector("button");
btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);
function myListener1(){
console.log("inside Listener 1");
}
function myListener2(){
console.log("inside Listener 2");
}
addEventListener is a method available on each HTML element. The first argument is the name of the event. In the above code the event is click. The second argument is the function I want to run when the listener fires when this event is recognized.
It is also possible to remove a listener:
var btn = document.querySelector("button");
btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);
function myListener1(){
console.log("inside Listener 1");
}
function myListener2(){
console.log("inside Listener 2");
}
setTimeout(function(){btn.removeEventListener('click',myListener1);
console.log("Listener 1 removed.");
},2000);
removeEventListener method allows to remove listener. In the above example, Listener 1 is removed after 2 seconds.
Consider the following code snippet
var btn = document.querySelector("button");
btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);
function myListener1(){
console.log("inside Listener 1");
}
function myListener2(){
console.log("inside Listener 2");
}
addEventListener is a method available on each HTML element. The first argument is the name of the event. In the above code the event is click. The second argument is the function I want to run when the listener fires when this event is recognized.
It is also possible to remove a listener:
var btn = document.querySelector("button");
btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);
function myListener1(){
console.log("inside Listener 1");
}
function myListener2(){
console.log("inside Listener 2");
}
setTimeout(function(){btn.removeEventListener('click',myListener1);
console.log("Listener 1 removed.");
},2000);
removeEventListener method allows to remove listener. In the above example, Listener 1 is removed after 2 seconds.
No comments:
Post a Comment