Fisu
Fisu

Reputation: 3324

jQuery each() not working for Firefox, working in webkit

I have a function which detects the section of a single-page site the user is currently on and, depending on the variable passed to it, scrolls to the next section or the previous. This is working fine in Safari and Chrome. However, in Firefox, regardless of where the scroll position is, it treats the browser as if it's at scroll 0.

function scrollToSection(dir) {
    if( !$("body").hasClass("scrolling") ) {
        $("body").addClass("scrolling");

        var headerH = $(".page-header").outerHeight();
        var scrollTop = $("body").scrollTop();

        $("section").each(function() {
            var sectionH = $(this).outerHeight(true);
            var sectionOffset = $(this).offset();
            var sectionOffsetTop = sectionOffset.top - headerH;
            if( (sectionOffsetTop <= scrollTop) && (sectionOffsetTop + sectionH >= scrollTop) ) {
                var prevSection = $(this).prev();
                var nextSection = $(this).next();
                if( dir === "up" ) {
                    $.scrollTo( prevSection, {
                            duration : 1000,
                            offset : {
                                top : -50
                            },
                            onAfter: function() {
                                $("body").removeClass("scrolling");
                            }

                        });
                } else {
                    $.scrollTo( nextSection, {
                            duration : 1000,
                            offset : {
                                top : -50
                            },
                            onAfter: function() {
                                $("body").removeClass("scrolling");
                            }
                        });
                }
                return false;
            }
        });
    }
}

Upvotes: 0

Views: 672

Answers (3)

Darkito
Darkito

Reputation: 96

Try to change $('body') in $('body,html') . It should work

Upvotes: 0

Tom
Tom

Reputation: 582

FireFox needs the scrolltop set and read from the html element. Other browsers store this on the body element.

do:

var scrollTop = $("html,body").scrollTop();

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74420

Instead of:

$("body").scrollTop();

Try using:

$("body,html").scrollTop();

Upvotes: 1

Related Questions