user899205
user899205

Reputation:

How can I improve this Javascript, for attaching events to all elements in page?

I'm developing a web application and I need to capture all events of all elements, I write a code myself, but I need you lovely experts to improve my code's performance as much as you can.

// Create mouse event callbacks and an array to store callbacks,
// This array is to prevent creation of callback functions multiple times
var mouseEventCallbacks = {};
var mouseEvents = [
    'mouseover', 
    'mouseout', 
    'mousedown', 
    'mouseup', 
    'click', 
    'mousemove', 
    'contextmenu', 
    'dblclick', 
    'mousewheel'
];

function mouseEventCallback(eventType){
    if(!mouseEventCallbacks[eventType])
        mouseEventCallbacks[eventType] = function(event) {
            self.port.emit('new-event', {
                x: event.pageX + window.pageXOffset, 
                y: event.pageY + window.pageYOffset
            },{
                type: eventType
            });
        }

    return mouseEventCallbacks[eventType];
}

// Attach all events to all elements
var elems = window.document.querySelectorAll('*');

for(var j = 0, s = elems.length; j < s; j++) {
    attachMouseEvents(elems[j]);
}

function attachMouseEvents(element){
    for(var k = 0, s = mouseEvents.length; k < s; k++){
        element.addEventListener(mouseEvents[k],
                                 mouseEventCallback(mouseEvents[k]),
                                 false);
    }
}

Upvotes: 4

Views: 289

Answers (2)

Ram
Ram

Reputation: 144659

you can use jQuery, and .bind events to all elements by using jQuery Universal Selector, however jquery * selector is extremely slow, and event delegation is preferred over .bind.

$("*").bind(events...)

http://api.jquery.com/bind/

David Flangan author of JavaScript: The Definite Guide says:

One of the difficulties of working with events is that IE (until IE9) implements a different event API than all other browsers do. To address this difficulty, jQuery defines a uniform event API that works in all browsers. In its simple form, the jQuery API is easier to use than the standard or IE event APIs. And in its more complex full-featured form, the jQuery API is more powerful than the standard API."

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

Instead of attaching event handler to each element, use event delegation. When event is triggered, it bubles in the DOM up to the body (or the first element that handle the event), so you han handle all events in the body's event handler. Then you have the event.target property with the reference to the DOM element that actually triggered it

P.S. I've linked jQuery documentation, but it's general advice and it's not just about using jQuery

Upvotes: 6

Related Questions