Expanding Elements on Scroll

Expand elements into a predefined area as they scroll into view. Good for images and similar elements.

by Travis Almand

HTML

<div class='box'><div class='red'></div></div>
<div class='box'><div class='white'></div></div>
<div class='box'><div class='blue'></div></div>
<div class='box'><div class='red'></div></div>
<div class='box'><div class='white'></div></div>
<div class='box'><div class='blue'></div></div>
<div class='box'><div class='red'></div></div>
<div class='box'><div class='white'></div></div>
<div class='box'><div class='blue'></div></div>
<div class='box'><div class='red'></div></div>
<div class='box'><div class='white'></div></div>
<div class='box'><div class='blue'></div></div>
<div class='box'><div class='red'></div></div>
<div class='box'><div class='white'></div></div>
<div class='box'><div class='blue'></div></div>
<div class='box'><div class='red'></div></div>
<div class='box'><div class='white'></div></div>
<div class='box'><div class='blue'></div></div>

CSS

div.box {
    background: rgb(69,72,77);
    background: -moz-linear-gradient(top,  rgba(69,72,77,1) 0%, rgba(0,0,0,1) 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(69,72,77,1)), color-stop(100%,rgba(0,0,0,1)));
    background: -webkit-linear-gradient(top,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%);
    background: -o-linear-gradient(top,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%);
    background: -ms-linear-gradient(top,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%);
    background: linear-gradient(to bottom,  rgba(69,72,77,1) 0%,rgba(0,0,0,1) 100%);
    border: 1px solid black;
    height: 200px;
    width: 100%;
}
div.box div {
    height: 100%;
    transform: scale(.5);
    transition: transform 1s;
    width: 100%;
}
div.red { background-color: red; }
div.white { background-color: white; }
div.blue { background-color: blue; }

JavaScript

// we expand the elements that are already in view
$('div.box').each(function () {
    if ($(this).offset().top < $(window).height()) {
        $(this).find('div').css('transform', 'scale(1)');
    }
});

$(window).on('scroll', function () {
    var scrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    
    $('div.box').each(function () {
        if (scrollTop > $(this).offset().top - windowHeight) {
            $(this).find('div').css('transform', 'scale(1)');
        }
    });
});