billylevin
billylevin

Reputation: 92

jQuery - Elements fade in/out on page scroll

I'm trying to make a page whereby, when you scroll down, an image fades out. Then, as you scroll down a little more, a new image fades in as it enters the page.

I have very small knowledge of jQuery, and so I did a search for solutions to this problem on this website. I found a piece of code and added it to the site, but it had zero effect on the website. Is this because images are being used.

Here is the code:

var subsectionTop = $('.sub-section').offset().top;

$(window).scroll(function () {
if ((subsectionTop - $(window).scrollTop()) < 20) {
    $('.sub-section').stop().fadeTo(100, 0);
} else {
    $('.sub-section').stop().fadeTo('slow', 1);
}
});

I am very stuck and would appreciate any help you guys could offer me. Thanks :)

P.S. here is a jsfiddle with all of my code

Upvotes: 0

Views: 2814

Answers (1)

srakl
srakl

Reputation: 2619

made some changes to your code and added jquery to your fiddle

<script>
$( document ).ready(function() {
         var subsectionTop = $('.sub-section').offset().top;

        $(window).scroll(function () {
            var y = $(window).scrollTop();
            if (subsectionTop < y) {
                $('.sub-section').fadeTo(100, 0);
            } else {
                $('.sub-section').fadeTo('slow', 1);
            }
        });
    });
</script>

Upvotes: 1

Related Questions