Home > Blockchain >  Run script when window is bigger than x, also when window is resized
Run script when window is bigger than x, also when window is resized

Time:03-04

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 am on desktop and start with a window smaller than 1245px; I want to be able to resize it and run that function and vise versa if I start with a larger 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?

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.

  • Related