In this tutorial i will show you how to create a menu that will stick if a certain height is triggered using jquery.
We will also assume that we have a 1st layer that is dynamically changing its height.
HTML example
<div id='div1'> Scroll Down </div>
<div id='menuLayer'>Home , About us , Contact Us</div>
<div id='content'>
The quick brown pusa
</div>
CSS example
#div1{
width:100%;
height:800px;
background:#333;
text-align:center;
Color:#fff;
}
#menuLayer{
width:100%;
height:50px;
background:#4679BD;
top:0px;
text-align:center;
line-height:50px;
}
#content{
width:100%;
min-height:2000px;
background:#D8E5CE;
}
First we will compute the 1st div
//get the height of div1
firstLayer = $('#div1').height();
After that we will determine if a user is scrolling
$(window).on('scroll', function() {
//get the current location of the page
var y_scroll_pos = window.pageYOffset;
});
Then we will determine if it reaches the end of our first div, we will change the css of the menu making it relative to fixed
//change to fixed if it reaches the bottom of #menuLayer
if(y_scroll_pos > firstLayer) {
$('#menuLayer').css( "position", "fixed" );
}
//change to relative if it reaches the top most of #menuLayer
if(y_scroll_pos < firstLayer) {
$('#menuLayer').css( "position", "relative" );
}
Check the demo to see all codes sum up.
LIVE DEMO
No comments:
Post a Comment