简体   繁体   中英

Kill and Load function based on different screen size javascript

I have code like:

function interactionScreen(){
   if ($(window).width() > 970) {  
      do something..
   } else if ($(window).width() < 970) {  
      do something..
   }
}

interactionScreen();   

$(window).resize(function() {
   interactionScreen();  
});

What I would like to achieve is that when the browser is resize to less than 970 then it will run other code. The issue is that when the page is load, script under > 970 will run first, if i resize the browser, both script > 970 and < 970 are run, just wondering if is there anyway to "destroy" the script and rerun the function?

You could wait until the browser window hasn't changed its size for at least x milliseconds before executing your function

var interactionScreen = (function(window) {
    var timer,
        w = $(window);

    return function(executeImmediately) {
        clearTimeout(timer);

        timer = setTimeout(function() {
                    var currentWidth = w.width();

                    if (currentWidth > 970) {
                        console.log("> 970");
                    } else {
                        console.log("<= 970");
                    }
                }, executeImmediately ? 0 : 200);
    };
}(window));

interactionScreen(true);

window.addEventListener("resize", function() {
    interactionScreen();
});

fiddle

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