RadiantHex
RadiantHex

Reputation: 25567

Catching any click performed using jQuery

The noob way to do it I guess would be

$('*').click(function(){...});

But is there any way I can catch any type of click, without having to register a listener for every object in the DOM?


Help would be amazing. =)

Upvotes: 31

Views: 38252

Answers (5)

Vincent Robert
Vincent Robert

Reputation: 36130

You can use event delegation on the document to catch all clicks.

jQuery will fill the target property of the event to retrieve the clicked element.

$(document).click(function(event){
  // event.target is the clicked object
});

Note that event.target will be the deepest element clicked. Ex: if there is a <span> in a <a>, you will get the <span>, not the <a>.

If you want to catch any click but want to retrieve a specific element (like a class), you can do:

$(document).click(function(event){
  $(event.target).closest(".clickable").each(function(){
    // "this" is your "clickable" clicked
  });
});

Unless an event handler on an element along the way does an event.stopPropagation() or return false, you'll get the click here.

Upvotes: 23

jasongetsdown
jasongetsdown

Reputation: 1305

$('*').click( function() {...} ) will only catch clicks on elements that existed when you made the call to .click(). To catch clicks on elements that may be created later you will need to bind to body or document as others have suggested.

Upvotes: 4

Mottie
Mottie

Reputation: 86413

How about just attaching a click to the body?

$('body').click(function(e){ ... })

The e.target should contain what was clicked on

Upvotes: 4

pkaeding
pkaeding

Reputation: 37643

How about:

$('body').click(function(){...});

Any click will be on the body, since that is the parent of all visible nodes in the dom.

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630429

A click event will by default bubble up the DOM, so you can just attach a click handler to the root, like this:

$(document).click(function() {
  //do something
});

Unless a handler on an element along the way does an event.stopPropagation() or return false, you'll get the click here.

Upvotes: 36

Related Questions