anoonimo anoonimo - 7 months ago 128
Javascript Question

Change CSS element with JQuery when scroll reaches an anchor point

I currently have this solution to change the css elements when the page reaches a certain point but I'd like to use an #anchor-point instead of the pixel value (1804) to be responsive on smaller screens. I know it must be easy but I can't find how:

$(document).scroll(function(){
if($(this).scrollTop() > 1804)
{
$('#voice2').css({"border-bottom":"2px solid #f4f5f8"});
$('#voice3').css({"border-bottom":"2px solid #2e375b"});
}
});


This is the current state: http://tibio.ch
Thank you,

Answer

Try this:

var targetOffset = $("#anchor-point").offset().top;

var $w = $(window).scroll(function(){
    if ( $w.scrollTop() > targetOffset ) {   
        $('#voice2').css({"border-bottom":"2px solid #f4f5f8"});
        $('#voice3').css({"border-bottom":"2px solid #2e375b"});
    } else {
      // ...
    }
});
Comments