cup_of cup_of - 7 days ago 6
jQuery Question

preform jquery function on browser shrink

Hello I have this function that preforms jquery on specific widths, I like it and it works fine but the only drawback is that the browser has to be refreshed for the function to kick in. Check my code below

function checkWidth() {
if (jQuery(window).width() < 1199) {
//do something
} else {

}
};
checkWidth();


So what this function says is that when the screen is below 1199 px, then preform the function but when you start out above 1199px then move the browser below 1199px, the page needs to be reloaded.

The point of this is to target tablet. I know that tablet cant go bigger than that so any time a user opens the page up on tablet this is not an issue, but I am a little picky and would like this to work when a user opens it up in a browser and then shrinks the browser.

Is it possible to modify this function so it will work on browser shrink instead of having to refresh?

Thanks!

Answer

You can use the resize event on window. The following will call your checkWidth() function every time a browser resize occurs:

$(window).on('resize', checkWidth);

But of course you can achieve this using media queries instead.