Adam Wojda
Adam Wojda

Reputation: 779

offset().top is giving wrong value

I'm using this js to add class to current section, and add class to current navigation element based on data attribute.

var cutoff = $(window).scrollTop(),
    cutoffRange = cutoff + 88,
    curSec = $('#main-page').find('.s-active'), // Current section
    curID = $(curSec).attr('id'), // Current section ID
    curNav = $('.navigation').find('li[data-navSections*="'+curID+'"]'); // Find current menu item

    $('.navigation li').removeClass('current-menu-item');
    $(curNav).addClass('current-menu-item');

$('.section').each(function(){

    if ($(this).offset().top > cutoff && $(this).offset().top < cutoffRange) {
        $('.section').removeClass('s-active')
        $(this).addClass('s-active');
        return false; // stops the iteration after the first one on screen
    }

});

This is example html

<section id="section-home" class="s-active"></section>
<section id="section-about" style="margin-top: 990px"></section>
<section id="section-section"></section>

#section-home {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    overflow: hidden;
    z-index: 1;
}

#section-about,
#section-section {
    z-index: 2;
    position: relative;
}

First seection is kind of parallax, margin-top to second section is added by another script.

The script above works great but doesn't add class to first fixed home section. Isn't this a bug with offset().top?


jsFiddle http://jsfiddle.net/f5ans6g6/

Upvotes: 0

Views: 720

Answers (1)

Rotan075
Rotan075

Reputation: 2615

It is a typo ;) Within this code: $('.section').each(function(){}); you are pointing to a class named .section. This is not available.

Try this:

$('section')

Upvotes: 3

Related Questions