3

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

18
  • try to add $(function(){ /* your js code here */ });. Commented Jul 24, 2014 at 15:37
  • @Aleksandar didn't try it, but it won't change anything. $(window) is defined before the DOM is ready. Commented Jul 24, 2014 at 15:38
  • 1
    Checking the console on your page gives the error: "undefined is not a function" on line 34 of index, which is the following line: if($(window).scrollTop() > 50) $("header").addClass("fixed"); Commented Jul 24, 2014 at 15:39
  • 3
    Your $ symbole is beign overriden. Use jQuery instead of $ Commented Jul 24, 2014 at 15:42
  • 1
    @SimonMathewson Try what Karl-Andre said, or wrap it in a self-executing function, passing jQuery as an argument. (function($) { /* Code here */ }(jQuery)) Commented Jul 24, 2014 at 15:45

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

Comments

1

Try using

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

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

1 Comment

Look at the comments of the OP.

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.