Simon Mathewson
Simon Mathewson

Reputation: 731

Change CSS at a certain scroll level via jQuery doesn't work

The following jQuery code:

Click here

HTML:
<header class="header">
    <div class="navbar">   
        Hello
    </div>
</header>

CSS:
.header {
        background-color: black;
        height: 1000px;
        width: 300px;
        color: white;
        text-align: center;
        padding: 30px;
    }

.fixed .navbar{
    border: 10px solid red;
    position: fixed;
    background-color: white;
}

.navbar {
    background-color: blue;
    height: 50px;
    width: 300px;
    color: white;
}

JS:
$(window).scroll( function(){
        if($(window).scrollTop() > 200) $("header").addClass("fixed");
        else $("header").removeClass("fixed");    
    });

does work.

But when I add it to my homepage, I have to refresh the page for the "fixed" class to be added. But I want the class to be added live, while scrolling down, without the page having to be refreshed. This works in jsfiddle, why doesnt it work on my page?

My page: Click here

Upvotes: 3

Views: 1174

Answers (2)

MisterBla
MisterBla

Reputation: 2395

As Karl-André said, your $ object is being overwritten. To make your code work you can do either of the following:

Use the jQuery object:

jQuery(window).scroll( function(){
    if(jQuery(window).scrollTop() > 200) jQuery("header").addClass("fixed");
    else jQuery("header").removeClass("fixed");    
});

Or wrap everything in a self-executing function, passing the jQuery object as an argument:

(function($)
{
    $(window).scroll( function(){
        if($(window).scrollTop() > 200) $("header").addClass("fixed");
        else $("header").removeClass("fixed");    
    });
}(jQuery))

Upvotes: 4

Shauno
Shauno

Reputation: 1258

Try using

$(function() {
    $(window).on('scroll', function(){
        if($(this).scrollTop() > 200) $("header").addClass("fixed");
        else $("header").removeClass("fixed");    
    });
});

http://jsfiddle.net/c9aXS/2/

Upvotes: 1

Related Questions