Detect window resizing and execute function using jquery

How can I make it so that every time the user resizes the window, the page performs a function?

+6
source share
5 answers

The following function should do what you need, it works in all browsers (except that it does not work when Safari is NOT maximized and resolution changes)

It starts when the window is changed again, as well as when the resolution changes , and also has a delay to avoid multiple calls when the user reconfigures the window.

var resizeTimer; //Event to handle resizing $(window).resize(function () { clearTimeout(resizeTimer); resizeTimer = setTimeout(Resized, 100); }); //Actual Resizing Event function Resized() { //Your function goes here }; 

Testing jsFiddle

+8
source

Regarding this article: https://developer.mozilla.org/en-US/docs/DOM/window.onresize

 window.onresize = resize; function resize() { alert('window size changed'); } 

window.resize makes this pretty simple.

+1
source

My suggestion. First HTML and CSS.

HTML

 <div id="wrapper"> <div id="div1"> #div1 content </div> <div id="div2"> #div2 content </div> </div> 

CSS

 div { color: white; margin: 20px; padding: 5px 18px; font: 700 16px/200% sans-serif; } #div1 { background-color: #d00; } #div2 { background-color: #27d; } 

Now jQuery :

For document only ( https://jsfiddle.net/sz7aeo9j/ )

 <script> $(document).ready(function () { var divone = $('#div1')[0].outerHTML var divtwo = $('#div2')[0].outerHTML $('#div2,#div1').remove(); if ($(window).width() < 640) { $('#div1').remove(); $('#wrapper').html(divtwo); } if ($(window).width() > 640) { $('#div2').remove(); $('#wrapper').html(divone); } }); </script> 

When resizing a window ( https://jsfiddle.net/sz7aeo9j/1/ )

 <script> $(document).ready(function () { var divone = $('#div1')[0].outerHTML var divtwo = $('#div2')[0].outerHTML $('#div1').remove(); $(window).resize(function () { if ($(window).width() < 640) { $('#div1').remove(); $('#wrapper').html(divtwo); } if ($(window).width() > 640) { $('#div2').remove(); $('#wrapper').html(divone); } }); }); </script> 
+1
source

you can register the onresize event in the window: the function is called when the window is resized

https://developer.mozilla.org/en/DOM/window.onresize

0
source

Use screen.width and screen.height to determine the width and height of the screen.

0
source

Source: https://habr.com/ru/post/894660/


All Articles