Search code examples
javascriptcsshtmlcss-positiononscroll

Change a div width on window scroll


I'm trying to make a javascript effect on a div like a garage door.
Basically I'd have an absolute div on the back and another div on the front which would shrink from bottom to top base on window school.

I've found a similar jsfiddle, but it's doing it on the width instead on the height and I'd like the div top to stay fixed and shrink from bottom to top.

JSFiddle Code

HTML
<div id="added">

<div id="container">
  My center div...
</div>

</div>

CSS
#added { 
    background: #eee;
    height: 2000px;
    overflow:hidden;
}
#container {
  width: 800px;
  height: 2000px;
  background-color: #567;
  margin: 0 auto;
  position:relative;
}

JS
$(window).resize(function() {
    $('#container').css({
        top: ($(window).height() - $('#container').outerHeight()) / 2
    });
});



// To initially run the function:
$(window).resize();


var $scrollingDiv = $("#container");
$(window).scroll(function() {
    var winScrollTop = $(window).scrollTop() + 0,
        zeroSizeHeight = $(document).height() - $(window).height(),
        newSize = 800 * (1 - (winScrollTop / zeroSizeHeight));

    $scrollingDiv.css({
        width: newSize,
        "marginTop": winScrollTop + "px"
    }, 500, 'easeInOutSine');
});

Any help will be appreciated.

Thank You


Solution

  • You can try that :

    var $scrollingDiv = $("#container"),
        defaultHeight = parseInt($scrollingDiv.css('height')); // whatever is in your css as
    $(window).scroll(function() {
        var winScrollTop = $(window).scrollTop() + 0,
            zeroSizeHeight = $(document).height() - $(window).height(),
            newSize = defaultHeight * (1 - (winScrollTop / zeroSizeHeight));
    
        $scrollingDiv.css({
            height: newSize,
            "marginTop": winScrollTop + "px"
        }, 500, 'easeInOutSine');
    });