Change CSS class after scrolling 1000px down
Asked Answered
H

2

5

I want a fixed menu to appear in the left column of my site once the user scrolls 1000px down, but am not very experienced with jQuery/JS. I thought something like this would work but it isn't doing anything:

HTML:

<div id="menu">[MENU_WILL_GO_HERE]</div>

STYLE:

#menu{display:none;}​

JQ:

var fixed = false;
 ​$(document).scroll(function() {
    if( $(this).scrollTop() > 100 ) {
        if( !fixed ) {
           fixed = true;
           $('#menu').css({position:'fixed', display:'block'});
        }
        } else {
           if( fixed ) {
               fixed = false;
               $('#menu').css({display:'none'});
        } 
    } 
});​

Q:

Is there a reason this doesn't work? The code is an example on http://jsfiddle.net/roXon/psvn9/1/, and even when I copy/paste that example exactly as it is into a blank html page, with a link of the latest jquery library, it still doesn't work like it does on that jsfiddle page. What could I be overlooking?

Hackbut answered 18/9, 2012 at 5:1 Comment(0)
K
17

Your braces are wrong in your example, but regardless, you can simplify your code:

CSS:

#menu {
    display : none;
    position : fixed;
}

JS:

 $(document).scroll(function() {
    $('#menu').toggle($(this).scrollTop()>1000)
 });​ 

Demo: http://jsfiddle.net/elclanrs/h3qyV/1/

Kraigkrait answered 18/9, 2012 at 5:7 Comment(4)
Even shorter: $('#menu').toggle($(this).scrollTop()>1000). jsfiddle.net/elclanrs/h3qyV/1Pernick
Ah good old toggle how did I neglect you? Honestly forgot it took a bool param. Good catch, friend.Kraigkrait
This does exactly what I want but I can't get the script to execute on any page. Does it need to be in a certain <script></script> tag or be before or after the HTML code? I can't figure out why it's not executing and it's the exact same code from the fiddle.Hackbut
@ZackTaylor: yes. You need to put <script type="text/javascript"> your code </script >.Plott
U
0

Edit like this

if( $(this).scrollTop() > 1000 )

you are looking for 1000px scroll,but it appears 100px due to this,from your code

Underbrush answered 18/9, 2012 at 5:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.