How to build simple sticky navigation using jQuery?

I am trying to change the css div while scrolling. This is my code, but unfortunately it will not work.

$(document).ready(function() {
   $(window).scroll(function () {
        if ($(this).scrollTop() > 150) {
            $('#subnav').css({
                'position' : 'fixed',
                'top' : '0'
            });
        } else {
            $('#subnav').css({
                'position' : 'static',
                'top' : 'auto'
            });
        }
    });
 });
+4
source share
1 answer

Try the following:

JsFiddle works here

$(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 only one value, you can use else, but if you have several values, I suggest not to use else, because it creates a conflict, use else ifintead.

+4
source

All Articles