Roaming Bear Roaming Bear - 4 months ago 7
Javascript Question

Detect point of screen size changes

I want to detect the point when the screen width changes to below 1120, and fire a piece of code, but to only do it when the screen size passes that point. I do not want to run the code when there is a change from, for example, 1000 to 999. Only from 1121 to 1120.

Answer

To ensure that your code doesn't run every time your browser is resized, but only when it changes above or below 1200px resolution, you can use a boolean(true/false) flag an only run your code when its value needs to change, in this case the under1200 variable.

No libraries are required if you're using this code.

var under1200=false;
    if(window.innerWidth<1200){
    	under1200=true;
    }
    window.onresize = function(event) {
    	if(under1200 == false && window.innerWidth<=1200){
    		console.log("Size under 1200");
    		under1200=true;
    		
    		//YOUR CODE FOR LESS THAN 1200px HERE
    	}
    	if(under1200 == true && window.innerWidth>1200){
    		console.log("Size over 1200");
    		under1200=false;
    		
    		//YOUR CODE FOR +1200px HERE
    	}
    }