File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes HTML, CSS and JavaScript and the fly likes Triggering jQuery events without knowing the selector to trigger? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Triggering jQuery events without knowing the selector to trigger?" Watch "Triggering jQuery events without knowing the selector to trigger?" New topic
Author

Triggering jQuery events without knowing the selector to trigger?

Rob Dennett
Ranch Hand

Joined: Dec 07, 2010
Posts: 81
Is it possible to trigger a custom event without knowing what selector the event was bound to? For example, let's say I have the following binding:

$('#foo').bind('myCustomEvent', function() { // do stuff });

Can I trigger this without knowing about "#foo"? That is, can I do something like $(document).trigger('myCustomEvent'); to get the above to fire? I know that the previous trigger doesn't work, but perhaps there is something similar?

Thanks,
Rob
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

The event can be triggered on any element that is a descendent of the bound element.

If you can't know that the element that you use as a trigger is a descendant or not, you could, of course, use "body *" to trigger the event on every element in the body.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

Of course, using the * approach means that the handler will trigger for the bound element as well as the propagation of the event from all its descendants. You can check to make sure that the current element and the target are the same to only perform the handler's action on the bound element.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61316
    
  66

Consider:
 
GeeCON Prague 2014
 
subject: Triggering jQuery events without knowing the selector to trigger?