0

I'm trying to animate (fade in) several headings on a page as the user scrolls to them, but when I reach the first one it fades them all in, regardless of whether I've reached them yet.

Could somebody help me to figure out where I'm going wrong? The jQuery looks like:

$(window).scroll( function(){

    $('.section').each( function(i){

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

        if( $('hgroup').is('.heading1') && bottom_of_window > bottom_of_object ){

            $('.heading1').animate({'opacity':'1'},1000);                 
        }
        if( $('hgroup').is('.heading2') && bottom_of_window > bottom_of_object ){

            $('.heading2').animate({'opacity':'1'},1000);                 
        }
    });         


});

And the markup:

<section class="section">
<hgroup class="heading1">
    <h1>Title</h1>
    <h2>Sub-Title</h2>
</hgroup>
</section>
<section class="section">
<hgroup class="heading2">
    <h1>Title</h1>
    <h2>Sub-Title</h2>
</hgroup>
</section>

1 Answers1

0

When you do a conditional to determine if hgroup is heading1 or heading2 or whatever, you are not specifying a specific hgroup so the conditionals will always be true (assuming that a heading1 or heading2 exists on the page. So those .is conditionals are useless.

EDIT: Do a console.write or an alert or breakpoints to look at the values of both heights as you go. See if you can find something weird.

e.g...

alert('Bottom of Object: ' + bottom_of_object + '\nBottom Of Window: ' + bottom_of_window);

Do that and put it in your scroll function so that when you scroll you can check out some values. That should lead you down the right road.

EDIT EDIT: See the 'correct' answer on this page: Check if element is visible after scrolling

Community
  • 1
  • 1
shubniggurath
  • 956
  • 1
  • 15
  • 31