1

I want to add some class for specify element when i'm scrolling my page/window, so i use offset for this but it's not warking - what is wrong? Much thx for help. This is my code:

$(window).scroll(function() {
    var top_offset = $('body').offset().top;
    if ((top_offset >= 40)) {
        $('nav').addClass('docked_nav');
    }
});

3 Answers 3

3

You have already fetched the offest value in the variable top_offset, it contains numeric value now and is not an object. So either use

if (top_offset>= 40) {
        $('nav').addClass('docked_nav');
    }

Or dont use any variable

if ($('body').offset().top >= 40) {
        $('nav').addClass('docked_nav');
    }

Arun Killu's answer is also need to be considered

Sign up to request clarification or add additional context in comments.

4 Comments

yeah i have mistake but i'v corect it and it still not working :(
how are you checking that it is not working? Can you create a sample fiddle
this is nice, but no i have allert for every mouse move :)
Thats because 40 is a small value for scroll. Try giving a large value e.g. 150 to test. This will depend upon your requirement
1
$('.nav').addClass('docked_nav'); if nav is a class or `#nav` if nav is id

Comments

0

I'm going to assume that you're taking the offset of body from the top when window is the actual scrolling element. In this case, you may want to get the scroll position of the window by calling a function like the following:

function getWindowScrollPos() {
    return (window.pageYOffset !== undefined) ? window.pageYOffset :
    (document.documentElement ||
     document.body.parentNode ||
     document.body).scrollTop;
}

If you're trying to make a element or several elements sticky (stick to the top), you can easily use this library I created to handle just that without you having to worry what's going on under the hood:

https://github.com/vhiremath4/Balloon

EDIT:

Just in case it wasn't clear, you're going to want to call that getWindowScrollPos function and assign it to top_offset instead of using jQuery's offset method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.