Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach event handlers for click event on all elements in the DOM

I want to be able to figure out which part of my page has been clicked. There is no guarantee the elements are all on the page from the get go, which means that I need to use something like jQuery delegate.

One way to do this is to iterate through all elements in the DOM and then attach an event handler to each element - but this will be slow and complicated - every time new html is dynamically added, I'd have to either re-attach all the handlers, or figure out the subset of html that was added.

The other way is to use event bubbling - so add an event handler to the document, or body and rely upon the events bubbling up.

Something like this:

$('body').delegate('div', 'click', function(e){
    dummyId++;
    console.log(e);
    console.log(e.currentTarget);
    console.log("=====");

});

However, after using this code, when I click on buttons on my page, I get the div surrounding the button, as opposed to the actual button. In other words, the above is too specific. Furthermore, I feel like the original selector should be the document, rather than the body tag.

To be clear, I want to know when any element is clicked on my page - how do I do that?

So I tried this code with .on:

$(document).on('click', function(e){
    console.log("EVENT DUMMY ID");

    console.log(e.target);
    console.log("=====");

});

However, when I click on buttons in my app, nothing gets triggered - when I click on other elements, the console logs run.

I understand this is probably hard to answer without more context - what else do you need?

like image 277
praks5432 Avatar asked Dec 15 '22 00:12

praks5432


1 Answers

currentTarget returns the node to which the event has bubbled (if at all). Instead, interrogate target, so:

Vanilla:

document.addEventListener('click', function(evt) {
    alert(evt.target.tagName);
}, false);

jQuery:

$(document).on('click', function(evt) {
    alert(evt.target.tagName);
});

http://jsfiddle.net/qsbdr/

like image 105
Mitya Avatar answered Apr 09 '23 19:04

Mitya