Search code examples
javascriptjqueryscopeeventtriggerstrict

jquery event trigger not working


I have two scripts.

The first script holds a prototype class of a game. This class is with use strict and isn't surrounded by document ready. The trigger:

$("#trigger").trigger("noPossibilities");

In the second script, which also has use strict, I try to catch the trigger:

$(document).ready(function() {
    $("#trigger").on("noPossibilities", function() {
        console.log("noPossibilities trigger");
    });
});

The problem is that I can't catch the trigger. This has probaly something to do with use strict/scope but I can't seem to find a way around this.

Really hope someone can help me

UPDATE The first script has a prototype class.

This class is getting instantiated in the second script. After the handler. Then it still doesn't work because the first script is loaded before the second script?

Also when I execute this line from the console:

$("#trigger").trigger("noPossibilities");

It doesn't get triggered. Shouldn't it work this way?

UPDATE 2

I found the problem. The first script adds the element with id trigger to the document when it is instantiated. I have a popup at the beginning of the game. Now the handler is getting attached on the click of that button.

The document probaly didn't have the element on which the handler should have gotten attached to. Now it is being attached later on and now it's working.


Solution

  • The issue is not with the scope, you are triggering the event before the handler is attaching to the element. The code inside document ready handler executes only after the DOM elements are loaded. In case you are triggering immediately after the script then it won't work since the elements are still loading.

    You can check the working of triggering within a different context by moving it to another document ready handler(to execute only after handler attached).

    $(document).ready(function() {
      $("#trigger").on("noPossibilities", function() {
        console.log("noPossibilities trigger");
      });
    });
    
    
    $(document).ready(function() {
      $("#trigger").trigger("noPossibilities");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="trigger"></div>