Ralph
Ralph

Reputation: 132

Scroll: change opacity (from 0 to 1 and vv) of div when at a specific position on page

Before posting this question I've searched for possible answers but couldn't find what I need.

That said: I have a demo page with multiple divs and every div can have a different height. What I've been stuck on for hours is a way to do the following:

When the bottom of a div meets a specific page top offset threshold while scrolling down, the opacity should change to .4 When scrolling up and the div is vertically in center again, then turn the opacity to 1.

The desired result is that 1 div is active (100% opacity), vertically in center and all the other divs inactive but when you scroll up/down enough the active div should become inactive (opacity 40%) and the next/previous div should become active.

It's imporant to note that the offset should be calculated based on the position of the bottom of the div. Because otherwise a div with a large height might get inactive when scrolling. Calculating from the bottom position should make sure that the entire div is out of center enough to become inactive.

Check this fiddle: https://jsfiddle.net/4q98yxk2/3/

Code:

    <script
    src="https://code.jquery.com/jquery-2.2.4.js"
    integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
    crossorigin="anonymous"></script>

    <script type="text/javascript">
    $(window).on("load",function() {
    $(window).scroll(function() {

    $(".fade").each(function() {

    console.log($(this).position().top);

    });
    }).scroll(); //invoke scroll-handler on page-load
    });

    </script>

    </head>
    <body>

    <div class="content">

    <div class="fade">Box 1</div>
    <div class="fade">Box 2</div>
    <div class="fade biggest">Box 3</div>
    <div class="fade">Box 4</div>
    <div class="fade blue">Box 5 blue</div>
    <div class="fade big">Box 6</div>
    <div class="fade">Box 7</div>
    <div class="fade">Box 8</div>
    <div class="fade big">Box 9</div>
    <div class="fade biggest">Box 10</div>
    <div class="fade">Box 11</div>
    <div class="fade">Box 12</div>

    </div>

Hope you can help because I've got no clue on how to achieve this. Thanks!

Upvotes: 0

Views: 1554

Answers (1)

DanielaB67
DanielaB67

Reputation: 442

I don't know much JS, but I think I found something. Please check the fiddle if it helps:

https://jsfiddle.net/scorpio777/4q98yxk2/25/

I've replaced your JS with this:

var fade = $('.fade');
var range = 200;
$(window).on('scroll', function () {
    var st = $(this).scrollTop();
    fade.each(function () {
        var offset = $(this).offset().top;
        var height = $(this).outerHeight();
        offset = offset + height / 1; 
        $(this).css({ 'opacity': 1 - (st - offset + range) / range });
    });
});

and added CSS:

.content{
  margin-top:50px;
}

Upvotes: 1

Related Questions