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

Share:
13,525
Enermis
Author by

Enermis

Updated on June 25, 2022

Comments

  • Enermis
    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.

    Fiddle

    • Mathletics
      Mathletics almost 10 years
      Amplify is an excellent, tiny library that will give you a global pub/sub system.
    • Enermis
      Enermis almost 10 years
      Thanks Amplify was exactly what i was looking for.
    • Conny Olsson
      Conny Olsson about 8 years
      Just change $.event.trigger({type:"custom"}); to $('*').trigger('custom');