Why is .trigger() not working when a selector is added to .on()?

246 views Asked by At

I have an html web page that uses .load() to dynamically add a header. I am also using firebase Auth for authentication which uses .onAuthStateChanged() to identify if a user is signed in or not. There are elements in both the main html document and dynamically added html that functions inside .onAuthStateChange() needs to interact with.

So, I am trying to create custom triggers within the .onAuthStateChange function. When I try adding a selector to the $(document).on('trigger','selector', function (){...}); it doesn't seem to work. If I do not use a selector (i.e. $(document).on('trigger', function (){...});) then it works... so the problem seems to be with the selector. I am not sure why the selector isn't working though. Or if triggers are really the best way to do this. Any and all help would be greatly appreciated!

Here's an abbreviated version of the code:

MAIN HTML:

<body>
  <header></header>
  <div class="calssName></div>

  <script>

      $(function(){
        $("header").load("header.html");
      });

      $(document).on('sgnIn','.calssName',function(){
         console.log("signed in");
         $(this).doSomeStuff;
      });

      $(document).on('sgnOut','.calssName',function(){
         console.log("signed in");
         $(this).doSomeStuff;
      });

     firebase.auth().onAuthStateChanged(firebaseUser => {
       if(firebaseUser) {  
         $(document).trigger('sgnIn');
       }
       else{
         $(document).trigger('sgnOut');
       }
    });
  </script>
</body>

HEADER HTML:

<div class="calssName>
</div>

ANSWER: I appreciate all the help, but in the end the best solution was to move to a framework (React or Angular) that was built specifically for this functionality. I could not get it to work with raw html and javascript.

2

There are 2 answers

0
Roko C. Buljan On

$(document) is just the delegateTarget, but the event will be bound to current or future '.calssName' elements, therefore you might want to do $('.calssName').trigger('sgnIn'); (instead of $(document).trigger('sgnIn');)

0
Shifrin On

You have to trigger the event on the element that the event is attached instead of $(document).

    <script>
        //...
        firebase.auth().onAuthStateChanged(firebaseUser => {
          if(firebaseUser) {
            $('.className').trigger('sgnIn');
          } else {
            $('.className').trigger('sgnOut');
          }
        });
    </script>