Toni Michel Caubet
Toni Michel Caubet

Reputation: 20173

following header on page scroll not following

i am trying to have the tipical menu following the webpage scroll,

i wanted to change the position relating the marginTop with the page scroll,

$(document).ready(function(){

    $(window).scroll(function(){
        var v= $(document).scrollTop();
        console.log(v);
        if(v>50){
            $('.menu').css({'marinTop':v+'px'});
            console.log(true);
        }else{
            $('.menu').css('marginTop','50px');                        
            console.log(false);
        }
    });
});

but it just wont move the bar... :s

Upvotes: 0

Views: 377

Answers (1)

Philippe Plantier
Philippe Plantier

Reputation: 8073

Here:

$(document).ready(function(){
    $(window).scroll(function(){
        var value = $(window).scrollTop();
        if(value>+$('.menu').css('marginTop').replace(/px$/, "")) {
            $('.menu').css({'position':'fixed','top': 0});
        }else{
            $('.menu').css('position','static');                        
        }
    });
});

Fixed 2 things:

  • Removed the ".px" (css("marginTop") returns "50px", which can not be compared to a number)
  • You should really use "position: fixed" instead of a javascript-updated "position: absolute"

Upvotes: 1

Related Questions