views:

57

answers:

2

I'm developing a touchscreen application that, aside from everything else, records the amount of times the screen is used so that the user can be reminded to clean the screen after a predefined number of clicks.

I've got the click functions written nicely, all I need now is make sure the function is called on a click.

I imagine $('*').click(function() { //do something }); would accomplish my goal, but is that the best way? Also, would that overwrite other click functions assigned to the elements?

+2  A: 

It would add, not override, but a better solution would be this:

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

Since clicks bubble, just listen up at the document level with one event instead of creating events on every element beneath. For the override part...you can add as many handlers as you want, they will just execute in the order they were bound.

Nick Craver
Thanks for the response, Nick. Will this potentially trigger my click function multiple times on one click, because of the bubbling? How would you avoid that? Perhaps pass the event to the function, and stop bubbling once it has been run once?
Gausie
Also, if this is used on document ready, will it apply to elements inserted into the DOM?
Gausie
@Gausie - This will not cause it multiple times whereas `"*"` would. In the `*` case, every element it bubbles through would fire it...but it can only reach document once at the very top so you don't need to worry about it with the `$(document)` approach.
Nick Craver
@Gausie - It'll handle new elements, whether new or old their events still bubble the same way...this is the basis for how `.live()` works in jQuery.
Nick Craver
Helpful and interesting; thanks Nick
Gausie
+1  A: 

The best way is to assign the event handler to document itself. The events bubble and document can catch them all, while still retaining the origin of the event.

Alsciende
Thanks for the response, but Nick got there faster. Still, +1 anyway
Gausie