简体   繁体   中英

Why the click event doesn't work twice on $(window).resize()?

I want to add a css class when I click on button if window width is less than 500px and another class if width is greater than 500px . I tried with the following:

$(window).resize(function(){ 
  if ($(window).width() > 500) {
      $(document).on('click','#btn',function(e) {
          e.preventDefault();
          $("#div").addClass("red");
          $("#div").removeClass("blue");
          runFunctionA(); //is different from FunctionB()
      });   
  } else {
      $(document).on('click','#btn',function(e) {
          e.preventDefault();
          $("#div").addClass("blue");
          $("#div").removeClass("red");
          FunctionB(); //is different from FunctionA()
      });
  };
});

Codepen Demo

The click works only if you resize the Codepen iframe window to <500 , but if is >500 doesn't work.

Any help is appreciated! Thank you so much!

Below code work based on window width,if window resize happen then you click the button at that time it will check client width and process the function

Try with this,

$(document).on('click', '#btn', function (e) {
    e.preventDefault();
    if ($(window).width() > 500) {
        $("#div").addClass("red");
        $("#div").removeClass("blue");
    } else {
        $("#div").addClass("blue");
        $("#div").removeClass("red");
    }
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM