Cameron
Cameron

Reputation: 28793

jQuery scrollTop always returning 0

I have the following HTML:

<div id="header">
</div>

<div id="content">
    <div id="test"></div>
    <div style="height:1280px;"></div>
</div>

jQuery

$(document).ready(function() {            
    $('#content').scroll(function(){
        console.log($('#test').scrollTop());

        if($('#test').scrollTop()<=100) {
            $('#header').addClass('shadow');
        }
        else {
            $('#header').removeClass('shadow');
        }
    });
});

Here's a fiddle: http://jsfiddle.net/sZ89D/

In it I have a fixed header that will have a class applied to it when the user scrolls a div with an id of test less than it's height (100px). The class is applied but doesn't removed again and console logging the code it turns out that scrollTop is always 0...

Any ideas what the issue is? Thanks

Upvotes: 3

Views: 13508

Answers (3)

MassivePenguin
MassivePenguin

Reputation: 3711

So you want the shadow to appear when you scroll down, and disappear when you scroll back to the top?

$(document).ready(function(){

            $('#content').scroll(function(){

                console.log($('#content').scrollTop());

                if($('#content').scrollTop()<=100)
                {
                    $('#header').removeClass('shadow');
                }
                else
                {
                    $('#header').addClass('shadow');
                }
            });

        });

Swap $('#test').scrollTop() for $('#content').scrollTop(), and reverse the add/remove class functions.

Upvotes: 5

Cameron
Cameron

Reputation: 28793

This works:

if($('#content').scrollTop()<=100)
                    {
                        $('#header').removeClass('shadow');
                    }
                    else
                    {
                        $('#header').addClass('shadow');
                    }

Based on comments from @MassivePenguin

Upvotes: 0

Jeffrey
Jeffrey

Reputation: 2005

Changing #test to #content seems to do the trick:

if($('#content').scrollTop()<=100)

Upvotes: 1

Related Questions