• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Triggering jQuery events without knowing the selector to trigger?

 
Rob Dennett
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic