1

I would like to apply the click event (or any other event) automatically to every HTML element on the page.

I am developing kind of a "clicking game" and would like to use one generic JavaScript function that will handle every click on every HTML element on the page.

Is this possible at all?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Trince
  • 59
  • 3
  • By "apply", do you mean "handle"? –  Sep 20 '15 at 11:49
  • 2
    jQuery has hijacked the term `bind` to mean something entirely different, and confusing to those who don't know the terminology. The correct term is "attach an event handler". –  Sep 20 '15 at 11:52

2 Answers2

3
document.addEventListener('click', function(e) {
    console.log(e.target);
}, false);

the e.target will give you the element that has been clicked.

Stranded Kid
  • 1,395
  • 3
  • 15
  • 23
  • Is it possible to pass "this" HTML element to the function? I mean for example:

    - so the P element is passed to the function. Or I should use tagName / localName attributes?
    – Trince Sep 20 '15 at 12:20
3

It's not only possible, it's trivial:

document.body.addEventListener("click", function(e) {
    // Use e.target for the clicked element
}, false);

Clicks "bubble" from the clicked element to its parent, then its parent, then its parent, etc., until they reach the document. (Unless an intervening event handler stops that via e.stopPropagation.) The above hooks the click on body (the container of all of your visible elements).

Note that the above works on all modern browsers, including IE9 and up in standards mode. It does not work on IE8 and earlier (or IE9 and later pretending to be IE8 or earier) because they didn't have addEventListener. You'd have to use the IE-specific attachEvent instead.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Why not bind directly the event on the document instead of the body? Does it changes anything? – Stranded Kid Sep 20 '15 at 11:27
  • 1
    `Clicks "bubble" from the clicked element to its parent, then its parent, then its parent, etc., until they reach the document.` unless event bubbling is prevented using `return false;` or `event.stopPropagation();` – Tushar Sep 20 '15 at 11:27
  • 2
    @Tushar: `return false` only does that under jQuery, but yes, unless propagation is stoppped by an intervening handler. – T.J. Crowder Sep 20 '15 at 11:28
  • 1
    @T.J.Crowder I just found you already answered my question on SO http://stackoverflow.com/questions/16029340/jquery-event-handling-bind-to-document-or-body-element – Stranded Kid Sep 20 '15 at 11:31
  • 1
    @Tushar: "Clicks bubble" is correct, not "Click bubble". I also refer to functions by their names, without `()`, and meant "document" as a word, not a symbol. – T.J. Crowder Sep 20 '15 at 11:41
  • @T.J.Crowder I was thinking about `click bubbles` – Tushar Sep 20 '15 at 11:46