0

I would like to add a class when the user scrolls to the top of a specific element.

I currently have this code but as you can see this is determined by the pixels from the top of the page. i would like it to be when the page scrolls to the top of an element as i am using percentages and making the site responsive so the pixels from the top of the page will vary dependant on the screen size.

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= 610) {
        $("header").addClass("header-animate");
    } else {
        $("header").removeClass("header-animate");
    }
});

Please let me know if you require any more details.

Thanks.

felipekm
  • 2,820
  • 5
  • 32
  • 42
DannyBoy
  • 1,604
  • 2
  • 13
  • 12
  • possible duplicate of [jQuery if myDiv is:visible, addclass to another element](http://stackoverflow.com/questions/7450203/jquery-if-mydiv-isvisible-addclass-to-another-element) – dschu May 08 '14 at 14:04

2 Answers2

0

What you should do is use the elements class or ID and get how far it is from the top :

*Note you may have to switch around whether it should be > 0 or < 0

if (scroll - $('#someElement').position().top > 0) {
    $('.header').addClass('header-animate')
}else {
    $('.header').removeClass('header-animate')
}
Adjit
  • 10,134
  • 12
  • 53
  • 98
0

You can do as below:

var element = $('.element').offset().top;
$(window).scroll(function(){
    if ($(this).scrollTop() > element){         
        $('.navigation').addClass('header-animate');         
    }
    else{        
        $('.navigation').removeClass('header-animate');        
    }
});
felipekm
  • 2,820
  • 5
  • 32
  • 42