Search code examples
jqueryresizejquery-click-event

Jquery - Click event on resize() not work properly


I have a problem with jquery's resize() method and click event: in the example below, resizing the window, the click event only works in a some pixels. For example, resizing width of window one pixel at a time will work some times yes some times not. Why this behavior?
if I take the click event out of my code, toggleClass works fine for every pixel.
I have tried with both firefox and chrome.

EDIT: I need the click to work only when the window width is resized below a given size.

jquery:

  $(document).ready(function(){
    $(window).resize(function() {
      if ($(window).width() < 1000) {
        $(".button").click(function() {
          $("#box").toggleClass("open");
        });  
      }
    });
  });

css:

#box {
  width: 300px;
  height: 300px;
  background-color: red;
}

#box.open {
  background-color: green;
}

html:

<body>
  <div id="box"></div>
  <button class="button">Click</button>
</body>

Example on Fiddle


Solution

  • This is because you're adding multiple click events every time the window is resized, so after a few resizes, one single click will toggleClass, toggleClass, toggleClass... times how many pixels window was resized.

    $(window).resize(function() {
      // Every time window resize do this:
    
      // Add new click event
      $(".button").click(function() {
        $("#box").toggleClass("open");
      });  
    });
    

    -- Edit --
    If it's just for a specific window size, you don't really need the resize part.
    You can just check the window size on every click.
    This should be enough:

    $(document).ready(function() {
      $(".button").click(function() {
        if ($(window).width() < 1000) {
          $("#box").toggleClass("open");
        }
      });
    });
    #box {
      width: 300px;
      height: 300px;
      background-color: red;
    }
    
    #box.open {
      background-color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="box"></div>
    <button class="button">Click</button>