Ganesh Yadav
Ganesh Yadav

Reputation: 2675

Fixed menu position top on scroll

Menu is fixed and and offset from top height of header. but when I scroll header goes up because it's not fixed. So menu should also go up on scroll.

find demo here

I just want there should be no offset margin from top on menu when scroll down.

$(window).scroll(function(){
  var y = $(window).scrollTop();
  var bgp = $(window).scrollTop();
  var mtv = $('.menu').position().top;
  if(y > 0){
    $('.menu').css({'top': + mtv-bgp +'px'});  
  } else{
    $('.menu').css({'top': + bgp-mtv+'px'}); 
  }
});

Upvotes: 0

Views: 2298

Answers (1)

Moneer Kamal
Moneer Kamal

Reputation: 1877

if i get what you want correct then this should help you:

body{
    margin:0;
    padding:0;
}
.header{
    background:#ddd;
    height:80px;
    position:relative;
}
.container{
    height:1000px;
    background:#eee;
    position:relative;
    width:100%;
}
.menu{
    background:#000;
    width:200px;
    height:100%;
    left:0;
    top:80px;
    position:fixed;
    z-index:11;
    transition: all 0.6s ease;
}
#toggle{
    width:50px;
    height:50px;
    background:yellow;
    float:left;
    margin:10px 20px;
}

and the js

   $(window).scroll(function(){
      var y = $('body').scrollTop();
      if(y > 80){
        $('.menu').css({'top':'0px'});  
      } 
        else if(y<80)
            $('.menu').css({'top':'80px'}); 
    });

i also updated your fiddel : https://jsfiddle.net/g6wfy740/2/

Upvotes: 1

Related Questions