32

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
  • 183,160
  • 33
  • 252
  • 304
Rich
  • 1,076
  • 3
  • 16
  • 34

4 Answers4

41

You can use the window onresize event:

window.onresize = setEqualHeight;
udidu
  • 7,805
  • 6
  • 46
  • 65
23

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

window.onresize = setEqualHeight;

or

window.addEventListener('resize', setEqualHeight);
Community
  • 1
  • 1
dougajmcdonald
  • 18,151
  • 10
  • 52
  • 89
18

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,691
  • 1
  • 12
  • 21
14

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

$(window).resize(function () {
    setEqualHeight( $('#border') );
});
Gabriele Petrioli
  • 183,160
  • 33
  • 252
  • 304