Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Event Handler for all events javascript/jQuery

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:

  1. How do I register a single listener for multiple events in pure javascript?

  2. 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
});
like image 622
ATOzTOA Avatar asked Dec 24 '12 09:12

ATOzTOA


People also ask

How do I add event listener only once?

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.

Can you have multiple event handlers?

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.

Which jQuery event occurs when add one or more event handlers on the specific child element of matching elements?

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.

Can you have multiple event listeners of the same type?

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.


1 Answers

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);
like image 168
Akhil Sekharan Avatar answered Sep 21 '22 15:09

Akhil Sekharan