Dylan Sowtis
Dylan Sowtis

Reputation: 39

Change DIV opacity based on how much is Visible

I'm trying to change the opacity of a DIV based on how much is visible (height-wise) in the window. For example if 50% of the DIV is visible in the window then the opacity should be .5

Here is what I've got, I know it's amateur and not optimal code. It's my math that is the problem. When the DIV is roughly 50% on the screen, with my calculations it comes out to around 80%

$(window).scroll(function () {
    var block = $('.block')
    var blockHeight = block.outerHeight();
    var bottom_of_block = block.offset().top + blockHeight;
    var blockOpacity = 0;
    if (bottom_of_block < ($(window).height() + $(window).scrollTop())) {
        // Sets opacity to 1 if div is completely on screen
        blockOpacity = 1;
    } else {
        // This is the math that I cant figure out completely
        blockOpacity = ($(window).height() + $(window).scrollTop()) / (bottom_of_block);
    }
block.css('opacity', blockOpacity);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 500px"></div>
<div class="block" style="background: blue;height: 220px;width: 220px;"></div>

Upvotes: 1

Views: 407

Answers (1)

Vivek Athalye
Vivek Athalye

Reputation: 2979

I think you need to calculate blockOpacity like this:

blockOpacity = ($(window).height() + $(window).scrollTop() - block.offset().top) / blockHeight;

Upvotes: 2

Related Questions