jquery trigger custom global event
13,525
I'm not sure I understand your question, but if you change your code to this:
$("#A").on("click", function(){
$(document).trigger("custom");
});
$(document).on("custom", function(e){
$("#B").removeClass("hidden");
});
$(document).on("custom", function(e){
alert("something");
});
It should work. Here's a demo
Author by
Enermis
Updated on June 25, 2022Comments
-
Enermis almost 2 years
I would like to do something like this
$("#A").on("click", function(){ $.event.trigger({type:"custom"}); }); $("#B").on("custom", function(e){ $("#B").removeClass("hidden"); }); $("#C").on("custom", function(e){ alert("something"); }
Where I trigger a custom event using JavaScript. I would then like to be able to use the
.on
function on different elements throughout the page. Clicking the "#A" would then trigger the event for all registered elements.I noticed that the trigger function is called on an element instead of globally, which is not what I want.
-
Mathletics almost 10 yearsAmplify is an excellent, tiny library that will give you a global pub/sub system.
-
Enermis almost 10 yearsThanks Amplify was exactly what i was looking for.
-
Conny Olsson about 8 yearsJust change $.event.trigger({type:"custom"}); to $('*').trigger('custom');
-