2

I'm using the below jquery to check and reset the height of my div on resize. However, there is a terrible freeze/lag when using the below code. The structure is just three absolutely positioned divs. One at the top, one at the bottom, and one in the middle. Any idea why this might be happening?

$(window).resize(function () {
            if ($("#master_bodywrapper_div").height() < 500) {
                $("#master_bodywrapper_div").height(500);
            }
            else {
                $("#master_bodywrapper_div").height("auto");
            }
        });
steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • 1
    Well, it *is* querying the DOM twice every time `resize` is triggered and this function called, which might be the source (DOM querying can be expensive). Note that `resize` is triggered *a lot* even if you simply grab the edge and move your mouse (with a moderate speed) 200px to one side. Try moving the `$("#master_bodywrapper_div")` query to above the `resize` callback, cached in a `var`, and then use that var reference in your callback function. – ajp15243 Sep 19 '13 at 17:59
  • @ajp15243 That was an answer, wasn't it ? – Milche Patern Sep 19 '13 at 18:03
  • @MilchePatern Hah, yes, I was just distracted by work and wasn't sure I'd make it answer-worthy. – ajp15243 Sep 19 '13 at 18:12

2 Answers2

2

This is because, on some browsers, the resize event can fire dozens of times per second. You should have a resizing function that is called only after the window is done being resized, like so:

(function($) {
    var resizeTimer = false;

    function doResize() {
        if ($("#master_bodywrapper_div").height() < 500) {
            $("#master_bodywrapper_div").height(500);
        }
        else {
            $("#master_bodywrapper_div").height("auto");
        }
        resizeTimer = false;
    }

    $(window).on("resize", function() {
        if (resizeTimer) {
            clearTimeout(resizeTimer);
        }
        resizeTimer = setTimeout(doResize, 300);
    });
})(jQuery);

Hope this helps!

theftprevention
  • 5,083
  • 3
  • 18
  • 31
1

Well, it is querying the DOM twice every time resize is triggered and this function called, which might be the source (DOM querying can be expensive). Note that resize is triggered a lot even if you simply grab the edge and move your mouse (with a moderate speed) 200px to one side. Try moving the $("#master_bodywrapper_div") query to above the resize callback, cached in a var, and then use that var reference in your callback function.

var div = $("#master_bodywrapper_div");

$(window).resize(function () {
        if (div.height() < 500) {
            div.height(500);
        }
        else {
            div.height("auto");
        }
    });
ajp15243
  • 7,704
  • 1
  • 32
  • 38