0

I'm trying to accomplish the same effect as talked about here: Show Div when scroll position I'm even using the same code, only trying to fade in an img rather than a div. The effect works for the first image(fading in as it scrolls into view), but all subsequent images fade at the exact same time, making them fully visible upon scroll, rather than fading into view. Has anyone had this problem or can suggest what it is I'm doing incorrectly?

/* Every time the window is scrolled ... */
$(window).scroll( function(){

/* Check the location of each desired element */
$('.hideme').each( function(i){

    var bottom_of_object = $(this).position().top + $(this).outerHeight();
    var bottom_of_window = $(window).scrollTop() + $(window).height();

    /* If the object is completely visible in the window, fade it in */
    if( bottom_of_window > bottom_of_object ){

        $(this).animate({'opacity':'1'},500);

    }

}); 

});

If the rest of my code is needed, I can include it, but it doesn't differ much from the original fiddle this code excerpt is from: http://jsfiddle.net/tcloninger/e5qaD/

What I can't figure out is why the fiddle works properly when I replace the text with images, but my website doesn't. It's seemingly identical code with two different outcomes.

Here's my actual website so you can see what it is doing. The text should be fading in one at a time rather than all at once. http://trentguillory.com/testwebsite/index2.html

Community
  • 1
  • 1
Trent
  • 3
  • 1
  • 6

2 Answers2

0

I have no problems with using the same code with images. I swapped the div tags with the following: <img class="hideme" src="http://placehold.it/350x150"/> See this fiddle. Can you edit on this fiddle and give more info?

Erik
  • 128
  • 2
  • 14
  • Here's my website so far. You can see that all of the images fade at the same time. http://trentguillory.com/testwebsite/index2.html – Trent Jan 30 '14 at 22:52
0

The difference between your code and the JSFiddle samples is that position().top gives you the position of the element with respect to it's parent element.

Since the JSFiddles don't encapsulate their text within a DIV, their code calculates the distance of the text from the HTML's top, which means the scrolling effect works.

In your code, the distance between the image element from the parent element is always 0, so all of them show up at the same time.

Instead of

$(this).position().top

Use

$(this).offset().top

which gives the position of the element from the top of the entire page. This will work.

Nitin Khanna
  • 53
  • 1
  • 10
  • Well, this solves the problem, but due to my lack in reputation I can't even up vote it. – Trent Jan 31 '14 at 00:19