acl77 acl77 - 4 months ago 7
Javascript Question

Can't get js fadeIn() to work

Trying to figure out how I use the fadeIn() function when I scroll to the bottom of the page. It seems to be a reasonably common technique these days and I'd like to use it. My code is as follows, but I can't find a way to get the images to fade in.

var c = 0;

$(function() {
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {

c = c + 1;

if (c <= 7) {
$('#intro').html($('#intro').html() + '<ul><li><a target="_blank" href="http://mywebsite.com"><img src="images/filler.png" alt="" />Count = ' + c + '&raquo;</a></li></ul><br class="clear" />');
} else if (c == 8) {
$('#intro').html($('#intro').html() + '<br /><p><a target="_blank" href="example_page.html">Search historical stories</a></p>');
} else {
// do nothing
}

}
});
});

Answer

I think your first issue is the way you are detecting having scrolled to the bottom of the page. Have a look at this.

Javascript: How to detect if browser window is scrolled to bottom?

I've updated your code to demonstrate.

jsFiddle demo without fadeIn()

var c = 0;

$(window).scroll(function() {
    if((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
        c++;
        if (c <= 7) {
            $('#intro').html($('#intro').html() + '<ul><li><a target="_blank" href="http://mywebsite.com"><img src="images/filler.png" alt="" />Count = ' + c + '&raquo;</a></li></ul><br class="clear" />');
        } else if (c == 8) {
            $('#intro').html($('#intro').html() + '<br /><p><a target="_blank" href="example_page.html">Search historical stories</a></p>');
        }
    } 
});

You mention using fadeIn() in the question. Here's a demo of your code updated to use fadeIn()

jsFiddle Demo with fadeIn()

var c = 0;

$(window).scroll(function() {
    if((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
        c++;
        if (c <= 7) {
            var el = $('<ul><li><a target="_blank" href="http://mywebsite.com"><img src="images/filler.png" alt="" />Count = ' + c + '&raquo;</a></li></ul><br class="clear" />').hide().appendTo('#intro').fadeIn();
        } else if (c == 8) {
            var el = $('<br /><p><a target="_blank" href="example_page.html">Search historical stories</a></p>').hide().appendTo('#intro').fadeIn();
        }
    } 
});