Do you guys have a hard time fighting what is wrong with the script? Actually, when the resolution is less than 992px of the browser window, the event should work. By clicking the class is added. The problem is that the event works through time. That is, for example, I do resize windows, stopped at 768, the event worked. Slightly moved the browser, everything is no longer working. A little smaller window, again earned.

https://codepen.io/brezze/pen/ERONZN

Where is the mistake ?

<div class="wrap"> <div class="item"></div> <div class="item"></div> </div> $(window).on('resize', function() { if ($(window).width() <= 992) { $('.wrap').click(function(){ $('.item', this).toggleClass('open'); }); } }).trigger('resize'); 
  • everything works in kodopene as you described - ThisMan
  • 2
    Every time you change a window, you hang a new event handler on the button. Therefore, switching toggleClass is performed many times, respectively, the class will or will not depend on the number of handlers, namely, even their number or not even. Type console.log("click") inside the click handler. - Stepan Kasyanenko

1 answer 1

You need to understand that when resizing, the resize event is executed, often, not once, but several, which is why you fail when you have several resize events when the width is changed.

It is best to define only the width of the window in resize , and the rest of the functionality to render. Also check for width after pressing, and not in front of it.

Your example

 let currentWidth = $(window).width(); $(window).on('resize', function() { currentWidth = $(window).width(); }); $('.wrap').click(function() { if (currentWidth <= 992) { $('.item', this).toggleClass('open'); } }); 
 .item { height: 300px; width: 300px; background-color: blue; margin: 10px; } .wrap { display: flex; justify-content: center; } .open { background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrap"> <div class="item"></div> <div class="item"></div> </div>