4

I'm trying to change the css of a div when scrolling. This is my code but unfortunately it won't work.

$(document).ready(function() {
   $(window).scroll(function () {
        if ($(this).scrollTop() > 150) {
            $('#subnav').css({
                'position' : 'fixed',
                'top' : '0'
            });
        } else {
            $('#subnav').css({
                'position' : 'static',
                'top' : 'auto'
            });
        }
    });
 });
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
user1462382
  • 135
  • 1
  • 12

1 Answers1

4

Try this:

Here is working jsFiddle

$(document).ready(function() {
   $(window).scroll(function() {
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > 150) {
            $('#subnav').css({'position':'fixed','top' :'0px'});
        } else {
            $('#subnav').css({'position':'static','top':'auto'});
        }
    });
 });

Note: If you have just one value you can use else, but if you have multiple values i suggest to not use else, because it creates conflict, use else if intead.

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • in long jquery plugins, it happens to me too. it is working on jsfiddle but same thing not working on my plugin ((: so i am trying to be more careful. – Barlas Apaydin Aug 09 '12 at 08:31
  • try this version http://jsfiddle.net/rBGsX/ which is _identical_ except that it _doesn't use a variable_. **It works just the same!** – Alnitak Sep 04 '12 at 11:08
  • @Alnitak it is the same code what OP asked, it also works on me too but when it is inside a long function or with plugin usage, it starts to not work. Sorry can't prove it, but it happened to me too before. Bealive me i am really experienced with this issues: http://stackoverflow.com/questions/11971475/setting-css-value-limits-of-the-window-scrolling-animation/11971912#11971912 – Barlas Apaydin Sep 04 '12 at 12:18
  • Whatever you're doing, it's either 1. a misunderstanding, 2. a bug in the code, or 3. a bug in the browser. Semantically there is _no_ difference between `var a = expression; if (a)` and `if (expression)` – Alnitak Sep 04 '12 at 12:25
  • @Alnitak Yeah you are right, there is a bug in the code which i can't detect. I will be more carefull, next time. Thanks. – Barlas Apaydin Sep 04 '12 at 12:39