36

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>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Rich
  • 1,136
  • 3
  • 16
  • 36

5 Answers5

45

You can use the window onresize event:

window.onresize = setEqualHeight;
udidu
  • 8,269
  • 6
  • 48
  • 68
26

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

window.onresize = setEqualHeight;

or

window.addEventListener('resize', setEqualHeight);
Community
  • 1
  • 1
dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89
21

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);
});
Merec
  • 2,751
  • 1
  • 14
  • 21
14

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

$(window).resize(function () {
    setEqualHeight( $('#border') );
});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
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"));
Tom Warner
  • 3,193
  • 3
  • 17
  • 24