2

I want a div to be vertically fixed at a defined scrolllevel. I tried this:

HTML:

<div id='something'>Something! </div>

CSS:

#something { 
    position:relative;
}

JQuery:

$(window).scroll(function(){
    if ($window.scrollTop() > 50){
        $("#something").css({"top": ($(window).scrollTop()) -50 + "px"});
    }
});

Here is a demo: http://jsfiddle.net/1Blerk/3jacz/4/ (#something should do the same as #headerMenu, but after some scrolling)

And i do not want to change position to be fixed!

I am not really familiar with JQuery, so i guess it is just some parantheses or a selector or...

Thanks in advance!

AndrewMk
  • 623
  • 2
  • 6
  • 16
1Blerk
  • 162
  • 1
  • 3
  • 13
  • 1
    Look in your browser's error console. – Matt Ball Jun 30 '13 at 13:47
  • Possible duplicate of http://stackoverflow.com/questions/4676131/how-do-i-get-a-fixed-position-div-to-scroll-horizontally-with-the-content-using?rq=1 – jeremy Jun 30 '13 at 13:52
  • I think it is not really a duplicate, because all other attempts that i found (including the one you posted above) are solving the problem by changing position from absolute to fixed. (But the question may still be irrelevant, because my attempt to solve the problem did not work because of missing parentheses, and not because of doing something else than changing position) – 1Blerk Jun 30 '13 at 16:09

2 Answers2

3

You'll notice that when looking in your Javascript console, you'll get the following error:

Uncaught ReferenceError: $window is not defined

As @matt-ball said in the comments above, to encourage good code practice, please always look in the error console before asking for others' help. The issue with your code is that you're not selecting the global window with a jQuery selector. Instead, you're selecting a variable that doesn't exist. Try the following.

$(window).scroll(function(){
    if ($(window).scrollTop() > 50){
        $("#something").css("top", $(window).scrollTop() - 50 + "px");
    } else {
        $("#something").css("top", "0px");
    }
});

Additionally, you can change the second $(window) to $(this) if it seems easier to understand what's going on.

jeremy
  • 9,965
  • 4
  • 39
  • 59
  • It seems to be useful to have an "else"-part as well: `else { $("#something").css({"top": 0 + "px"}); }` Otherwise the position of the div can be wrong when scrolling back fast. – 1Blerk Jun 30 '13 at 15:13
  • Demo with if and else part: [link](http://jsfiddle.net/1Blerk/3jacz/6/) – 1Blerk Jun 30 '13 at 15:20
  • +1 else part is important man ! Thanks. – gprathour May 28 '14 at 16:20
2

You forgot to wrap $(window) in parenthesis.

FIDDLE

jeremy
  • 9,965
  • 4
  • 39
  • 59
Danield
  • 121,619
  • 37
  • 226
  • 255