paelzer
paelzer

Reputation: 115

jQuery: height() of a div and window resize

take a look and the following fiddle first and try out the overlay header. When you close the div and resize the window, the #overlay div starts to jump around an becomes visible even though it is closed. This is caused by the text in the #overlay div, since the div has no fixed height and is responsive. How can I alter my jQuery and stop this effect?

var overlayState = 'close';
var overlay = $('#overlay');

$(window).resize(function () {

    if (overlayState == 'close') {
        overlay.css({
            display: 'block',
            marginTop: -overlay.height()
        });
    } else {
        overlay.css({
            display: 'block',
            marginTop: 0
        });

    }
});

$(document).ready(function () {
    // var overlay = $('#overlay');
    var overlayControl = $('.overlay-controls a');
    var overlayicon = $('.overlay-controls span');

    overlay.css({
        display: 'block',
        marginTop: -overlay.height()
    });

    // var overlayState = 'close';

    overlayControl.toggle(function () {
        overlayState = 'open';
        overlayicon.addClass('open');
        overlay.animate({
            marginTop: 0
        }, 600, 'easeInOutQuart');

    }, function () {
        overlayState = 'close';
        overlayicon.removeClass('open');
        overlay.animate({
            marginTop: -overlay.height()
        }, 900, 'easeOutBounce');

    });
});

And here's the FIDDLE: http://jsfiddle.net/RS9yb/4/

Upvotes: 0

Views: 180

Answers (1)

adeneo
adeneo

Reputation: 318342

Just make sure you hide and show the element properly, and not just slide it up, and you'll avoid the issue completely:

overlayControl.toggle(function () {
    overlayState = 'open';
    overlayicon.addClass('open');
    overlay.show().animate({
        marginTop: 0
    }, 600, 'easeInOutQuart');

}, function () {
    overlayState = 'close';
    overlayicon.removeClass('open');
    overlay.animate({
        marginTop: -overlay.height()
    }, 900, 'easeOutBounce', function() {
        $(this).hide();
    });
});

FIDDLE

Upvotes: 1

Related Questions