Search code examples
jqueryjquery-1.4

jQuery click event not working on multiple screens


I am using jQuery 1.4.2. Using the CSS selector "span.accordionOn", I am handling a click event. On screen one, it is working fine. Where as when I navigate to next screen, the functions are not getting called.

The jQuery handlers are as shown below. I am keeping them in a js file and loading the js file for every page load.

 $("span.accordionOn").click(function(event){
    $(this).parents(".toggleOuterCustom");
    $(this).parents(".toggleOuterCustom").find(".lHeight").toggleClass('lHeighttranslate');
    return false;
  });




// toggle link icon
  $('span.accordionOn').click(function(){
    $(this).toggleClass('accordionOff');
  });

Solution

  • Without seeing more code it will be hard to find the exact issue, but here's a guess:

     $(document).on("click", "span.accordionOn", function(event){
        $(this).toggleClass('accordionOff'); //I merged the 2 functions
        $(this).parents(".toggleOuterCustom");
        $(this).parents(".toggleOuterCustom").find(".lHeight").toggleClass('lHeighttranslate');
        return false;
      });
    

    Try the above code. If this works then the issue is as following:

    • You bind the event handler to all span.accordionOn elements that are currently in the document
    • However, if you add new span.accordionOn elements after this, the event will not be bound to them
    • The on event will work for all current and future span.accordionOn items that will ever be in the document, which solves this issue