Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. =)

like image 891
RadiantHex Avatar asked Jul 18 '10 21:07

RadiantHex


People also ask

How do I get the clicked element in an event?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

What is trigger click in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

What does Click () do in Javascript?

click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.


2 Answers

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.

like image 166
Nick Craver Avatar answered Sep 28 '22 05:09

Nick Craver


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.

like image 36
Vincent Robert Avatar answered Sep 28 '22 05:09

Vincent Robert