mrilikecoding
mrilikecoding

Reputation: 75

JQuery adding class not working in Firefox

I'm a little new to JQuery, so forgive me if this is obvious.

I'm running this code to add/remove an "active" class to fixed nav bar list items as the user scrolls up and down a single page. It's working in Chrome and IE, but not in Firefox. Anybody know why?

Thanks!

// #div ids for page content
$(this).ready(function(){
var section0Height = $('#home').height();
var section1Height = $('#mission').height();
var section2Height = $('#services').height();
var section3Height = $('#team').height();
var section4Height = $('#contact').height();


// #li ids for nav items
$(window).scroll(function() {
    var winTop = $(window).scrollTop();
    if(winTop >= section0Height && winTop <= section1Height){
        $('#section0').addClass("active").not().removeClass("active");
    } else if(winTop >= section1Height && winTop <= section2Height){
        $('#section1').addClass("active").not().removeClass("active");
    } else if(winTop >= section2Height && winTop <= section3Height){
        $('#section2').addClass("active").not().removeClass("active");
    } else if(winTop >= section3Height && winTop <= section4Height){
        $('#section3').addClass("active").not().removeClass("active");
    } else if(winTop >= section4Height){
        $('#section4').addClass("active").not().removeClass("active");
    } 
  });
});

Upvotes: 1

Views: 1656

Answers (2)

redbmk
redbmk

Reputation: 4796

Here's a working fiddle based on the one you provided. Basically, instead of looking for the height of the div, you need to find the offset from the top of the document. When the window is scrolled down to that div then $(window).scrollTop() will match up with $(section).offset().top. The fiddle has some more comments to explain different parts, but here's the code for quick reference:

jQuery(function ($) {
    var links = $('#section0, #section1, #section2, #section3');

    $(window).scroll(function () {
        var winTop = $(window).scrollTop();

        $.each(links.removeClass('active').get().reverse(), function (idx, link) {
            var section = $( $(link).attr('href') );
            if (winTop >= section.offset().top) {
                $(link).addClass('active');
                return false;
            }
        });
    });
});

Upvotes: 0

adeneo
adeneo

Reputation: 318182

replace

$(this).ready(function(){ ...

with

$(document).ready(function(){ ...

jQuery .ready()

The .ready() method can only be called on a jQuery object matching the current document

Other than the fact that not() without a parameter, does nothing for you, it's the only reason I can spot for the posted code not to work?

Upvotes: 2

Related Questions