Call a function when window is resized
Asked Answered
C

5

38

How can I call for this(or any) JS function to be run again whenever the Browser window is resized?

<script type="text/javascript">
 function setEqualHeight(e) {
     var t = 0;
     e.each(function () {
         currentHeight = $(this).height();
         if (currentHeight > t) {
             t = currentHeight
         }
     });
     e.height(t)
 }
 $(document).ready(function () {
     setEqualHeight($(".border"))
 })
</script>
Cindiecindra answered 4/3, 2013 at 15:57 Comment(0)
Z
47

You can use the window onresize event:

window.onresize = setEqualHeight;
Zink answered 4/3, 2013 at 15:58 Comment(0)
T
27

You can subscribe to the window.onresize event (See here)

window.onresize = setEqualHeight;

or

window.addEventListener('resize', setEqualHeight);
Tammara answered 4/3, 2013 at 15:59 Comment(0)
D
20

This piece of code will add a timer which calls the resize function after 200 milliseconds after the window has been resized. This will reduce the calls of the method.

var globalResizeTimer = null;

$(window).resize(function() {
    if(globalResizeTimer != null) window.clearTimeout(globalResizeTimer);
    globalResizeTimer = window.setTimeout(function() {
        setEqualHeight();
    }, 200);
});
Diacaustic answered 4/3, 2013 at 16:3 Comment(1)
big up for reducing calls of the methodAviary
T
14

You use jquery, so bind it using the .resize() method.

$(window).resize(function () {
    setEqualHeight( $('#border') );
});
Tuck answered 4/3, 2013 at 16:1 Comment(0)
L
0

Javascript has recently added support for the ResizeObserver API which allows you to bind a callback to any specific element (especially useful if you want to target particular elements which may be resized even if the whole page isn't); however, you can also use it to target the whole document by passing in the root element.

const resizeObserver = new ResizeObserver((entries, observer) => {
  // if necessary, you can do something with the entries which fired the event, 
  // or the observer itself (for example stop observing an element)
  setEqualHeight();
});

//to attach to the whole document
resizeObserver.observe(document.documentElement);

//to attach to specific target element(s)
resizeObserver.observe(document.querySelector(".container"));
Libration answered 13/6, 2023 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.