I have a jQuery script that I want to run only if the window is wider than 1245px.
if ($(window).width() > 1245) {
// script
}
This is for responsive reasons. But Let's say I'm on desktop and start with a smaller than 1245px window, I want to be able to resize it and gain the functionality and vise versa if I start with a bigger window.
I have tried using 'resize' like this:
$(window).on('resize', function(){
var win = $(this); //this = window
if (win.height() > 1245) { /* ... */ }
}
But I run into problems with the script not running at the initial window size, what's the best way to approach this? Thanks
CodePudding user response:
Also add load
to the list of events:
$(window).on('load resize', ...
Be advised that resize event is fired continuously while window is being resized so for example if you resize it from 1000 to 1600px in one second it would fire 600 times. Using any expensive function will bog down the browser. I recommend using "debouncing" trick for resize events.