Calculate percentage of positioned elements for parallax opacity

http://stackoverflow.com/questions/14863346/calculate-percentage-of-positioned-elements-for-parallax-opacity

by GoranMottram

HTML

<div class="content">
    
    <div class="text">Hello World</div>
    
</div>
<div class="debug"></div>

CSS

body {
    height: 1400px;
    padding-top:700px;
}

.content {
    position: relative;
    height: 200px;
    background: blue;
}

.debug { position:fixed; top:0; right:0; }

JavaScript

$(document).ready(function() {
    setParalaxContent();
    
    $(window).scroll(function() {
        
        setParalaxContent();
    });
});

function setParalaxContent() {

    var p = {
        scrollTop: $(window).scrollTop(),
        windowHeight: $(window).height(),
        contentTop: $('.content').position().top,
        contentHeight: $('.content').height()
    };
    
    // determine scrollTop's bounds where content enters & exits the window
    p.lowerBound = p.contentTop - p.windowHeight;
    p.upperBound = p.contentTop + p.contentHeight;
  
    // determine scrollTop's position percentage (x2) in relation to bounds
    p.percent = (p.scrollTop - p.lowerBound) / (p.upperBound - p.lowerBound) * 2;
    
    $('.debug').html(p.percent);

    $('.content').animate({
        opacity: 1 - Math.abs(p.percent - 1)
    }, 1);
}