0

I copied the working solution code from this post:

Anchor highlight on scroll

It works fine in Chrome but not in Firefox.

Based on this post Animate scrollTop not working in firefox, I changed the $("body").animate to $("html, body").animate and now the scroll works but I can't figure out why the active link won't work.

HTML

<section id="1">1</section>
<section id="2">2</section>
<section id="3">3</section>
<section id="4">4</section>

<div id="menu">
<a href="#1">1</a>
<a href="#2">2</a>
<a href="#3">3</a>
<a href="#4">4</a>
</div>

jQuery

var timerid; //Used to fire scroll function once after scrolling is done.
$(document).ready(function(){
    $("#menu a").click(function(e){
        e.preventDefault();
        $("#menu a").removeClass('active');
    var id = $(this).attr("href").substring(1);
    $("html,body").animate({
        'scrollTop': $("section#" + id).offset().top
    });        
});
$("body").scrollTop(1); //forcing window scroll to execute on page load
$(window).scroll(function(){
    clearTimeout(timerid);
    timerid = setTimeout(checkactivelink, 50);
});

function checkactivelink()
{
    $("section").each(function(){
        if($("body").scrollTop() >= $(this).offset().top)
        {
            $("#menu a").removeClass('active');
                $("#menu a[href=#" + $(this).attr("id") + "]").addClass('active');
        }
    });
  }
});
Community
  • 1
  • 1
MPUserr
  • 45
  • 1
  • 4

1 Answers1

1

Use $(window).scrollTop() instead of $(body).scrollTop() as it is widely supported. Check out this fiddle in firefox to see it working: https://jsfiddle.net/vdpm674z/1/

function checkactivelink() {
    $("section").each(function(){ 
        if($(window).scrollTop() >= $(this).offset().top) {
          $("#menu a").removeClass('active');
          $("#menu a[href=#" + $(this).attr("id") + "]").addClass('active');
        }
    });
}
amespower
  • 907
  • 1
  • 11
  • 25