0

I have this kind of handler

$(".mydiv").on('click', function(e){

// some logic
$(this).toggleClass('active');

//other logic

});

I have a bug where this event is triggered twice, and I see that on the first run this is ".mydiv" and on the second run this is ".mydiv.active" and it seems that ".mydiv.active" is added during the event handling to the list of nodes that match the selector

Is there a way around this?

This is the fuller code:

$(".filter_view:not(.mobile-view) .filter_content .cat, .filter_view:not(.mobile-view) .filter_content .check_area, .mobile-view .search_filter").on("click", function(e){
        debugger;

        $(this).toggleClass("active");
                e.stopPropagation();

// rest of the logic

});

<span class="check_area col-xs-4 col-md-2">
    <input class="filter_checkbox" id="Neve" name="Neve" type="checkbox" value="Neve"> 
    <label class="filter_checkbox_label" for="Neve">Neve</label>
</span>

Basically, the parent is .filter_view, but on mobile it has a .mobile-view class, so on mobile I want the search_filter to do the logic and on not mobile when clicking on the check_area (which is checkbox + label) and on .cat (category)

When checking the event on the first and second triggers, the first target is the label (what I clicked) yet the 2nd time the target is the checkbox (which I didn't click)

Even though I stopped propagation, could it be that bootstrap (or some other framework lib) has an event of when a label is clicked the checkbox is click()ed as well?

Tim B
  • 40,716
  • 16
  • 83
  • 128
Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244

2 Answers2

0

try

$(".mydiv").on('click', function(e){

// some logic
$(this).toggleClass('active');

e.stopPropagation();

});

stopPropagation() prevents bubbling of the event.

Vizard
  • 303
  • 1
  • 8
0

Add $(".mydiv").off('click'); before you bind the click event, the code you showed us is probably being called twice, which binds the event handler twice. Maybe you have it in an init() function which is called more than once?

caffeinated.tech
  • 6,428
  • 1
  • 21
  • 40