简体   繁体   中英

How to execute a code only once after a certain condition has been met?

What I'd like to happen is to swap the content of 2 divs once the window has reached a certain width (1023px) but I don't want it to keep running the swapping code every time I resize the window after it has already reached that width (1023px):

$(window).resize(function() {

  if($(window).width() <= 1023) {      

    var $left_col = $('.about-left-col').html();
    var $right_col = $('.about-right-col').html();

    $('.about-right-col').html($left_col);
    $('.about-left-col').html($right_col);

  } 

});

Use ==

$(window).resize(function() {

  if($(window).width() == 1023) {      

    var $left_col = $('.about-left-col').html();
    var $right_col = $('.about-right-col').html();

    $('.about-right-col').html($left_col);
    $('.about-left-col').html($right_col);

  } 

});

You can set a simple variable (above you resize function) and check against it.

var wasResized = false;

Set it to true when resizing and add a check to you condition if it is true/false.

Use a global variable to store the state

var notChanged = true;

$(window).resize(function() {

  if($(window).width() <= 1023) {      
    if(notChanged) {//test if its not changed
    var $left_col = $('.about-left-col').html();
    var $right_col = $('.about-right-col').html();

    $('.about-right-col').html($left_col);
    $('.about-left-col').html($right_col);
     notChanged = false;//set it to false so the code doesn't trigger anymore 
    }
  } 

});

You can try like this,

$(window).resize(function() {

      if($(window).width() <= 1023) {      

        var $left_col = $('.about-left-col').html();
        var $right_col = $('.about-right-col').html();

        if($('.about-right-col').html() != $left_col){
            $('.about-right-col').html($left_col);
            $('.about-left-col').html($right_col);
        }else{
            return false;
        }
      } 

});

You could do something like this, have a counter on function execution using a closure and proceed as you need.

 $(window).resize(reposition); function reposition = ({ var count = 0; return function() { if (count !== 0) { return; } if ($(window).width() <= 1023) { var $left_col = $('.about-left-col').html(); var $right_col = $('.about-right-col').html(); $('.about-right-col').html($left_col); $('.about-left-col').html($right_col); count++; } }; })(); 

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