Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery executing both branches of an if-else statement in Rails

I have the following jQuery on a Rails page:

$(document).on('click','.reportsArrow', function() {
    if ( $(this).parent().hasClass('reportCollapsed') ) {
      console.log("A");
      $(this).parent().removeClass('reportCollapsed');
    }else{
      $(this).parent().addClass('reportCollapsed');
        console.log("B");
    }
});

When I click on an element with reportsArrow and without reportCollapsed, the log shows

B

A

Meaning it is executing the else part and then executing the if part. I want the function to only be executed once per click, and to only follow one code path. Why is it being executed twice and how do I stop this? I should point out that this toggles correctly in the mockups created by the web designer (on HTML/CSS/JS only). It looks like the problem is Rails related.

EDIT:

We have found a working solution:

$('.reportsArrow').click(function() {
    $(this).parent().toggleClass('reportCollapsed');
}); 
like image 471
Eric Baldwin Avatar asked Dec 05 '22 06:12

Eric Baldwin


1 Answers

The event would be getting fired more then once and propagated up-ward in the DOM tree. Use event.stopPropagation(). You can also use the toggleClass instead of branching.

$(document).on('click','.commonClass', function(event) {
   event.stopPropagation();
   $(this).parent().toggleClass('newClass');
});
like image 118
Adil Avatar answered Dec 09 '22 13:12

Adil