Jack Doyle Jack Doyle - 4 years ago 228
HTML Question

Multiple divs fade in/ out on scroll effect not working

I have a 3

div
s which are relatively positioned on the right side of my page inside an absolute parent div. I want them fade in and out as they scroll outside of they view (parent div). The the fade feature was working before I set my parent
div
s positioning. How do I fix this?

Here is a Codepen

<div class="container">
<div class="row">
<div class="col-sm-6" id="left_content">
<img src="buffalo.png">
</div>
<div class="col-sm-6" id="content">
<div class="right_content" id="box1">
<h4>Hi. My name is Jack.</h4>
<p>Scroll down for more info</p>
</div>
<div class="right_content" id="box2">
<h4>I'm a 21 year old developer living in Buffalo, Ny.</h4>
</div>
<div class="right_content" id="box3">
<h4>Hi. My name is Jack.</h4>
<p>Scroll down for more info</p>
</div>
</div>
</div>


JS:

$(window).scroll(function () {
$('[id^="box"]').each(function () {
if (($(this).offset().top - $(window).scrollTop()) < 20) {
$(this).stop().fadeTo(100, .5);
} else {
$(this).stop().fadeTo('fast', 1);
}
});
});


CSS:

#left_content {
position: fixed;
}
.right_content {
position: relative;
}
::-webkit-scrollbar {
display: none;
}
#content {
width: 45%;
height: 400px;
overflow: scroll;
position: absolute;
right: 0;
}
h4, p {
margin-left: 10%;
}
#box1 {
top: 250px;
}
#box2 {
top: 650px;
}
#box3 {
top: 1050px;
margin-bottom: 600px;
}

Answer Source

Your .scroll() is not on the proper area. Because you are actually scrolling your <div id="content"> and not the window itself, so adjust your script like so:

<script type="text/javascript">

    $('#content').scroll(function () {
        $('[id^="box"]').each(function () {
            if (($(this).offset().top - $(window).scrollTop()) < 20) {
                $(this).stop().fadeTo(100, 0.5);
            } else {
                $(this).stop().fadeTo('fast', 1);
            }
        });

    });

</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download