I know I can have one handler handle multiple events using jQuery like:
$('#myID').bind('blur mousedown mouseup focus', function (e) {}
Also, I can register an event from all elements using jQuery like:
$(document).on("click", "*", function(event) {
console.log("Click");
});
I have two questions:
How do I register a single listener for multiple events in pure javascript?
Is there any way to have a single handler for all events in a document using JS or jQuery, like a master handler which will delegate the events to my other handlers?
I am looking at something like this:
$(document).on("*", "*", function(event) {
console.log("I am the master handler...");
// call delegates
});
We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
Only one event handler can be assigned for every event in an element. If needed the handler can be replaced by assigning another function to the same property. Below we show how to set a simple greet() function for the click event using the onclick property.
delegate() Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
The addEventListener() methodYou can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
This is the closest i can get by javascript: JSBIN-Demo
<input type="text" id="myText" />
var allEvents = ['focus','blur','mouseover','mousedown','mouseup','mousemove', 'click'];
function masterHandler(){
var event = event || window.event;
switch(event.type){
case 'click':
console.log('cliked');
break;
case 'mouseover':
console.log('mouseover');
break;
}
}
function bindAllEvents(selector, handler) {
var elements = document.querySelectorAll(selector);
for(var i=0;i<elements.length;i++){
for (var key in allEvents){
elements[i].addEventListener(allEvents[key], handler, false);
}
}
}
bindAllEvents('*', masterHandler);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With