Reputation: 127
I want to do, when user descents down the page, nav-bar position is fixed. I change position jquery or css but the problem is that.
When user descents down the page:
I want to fixed on top of the page. Thanks for helping.
nav css: `
img#logo {width:auto;height:72px; position:absolute;margin-left:90px; }
div#nav {width:1930px;height:72px;border:2px solid #333;}
div#nav ul { list-style-type:none; }
div#nav ul li {float:left;}
div#nav ul#menu1 li a {font:20px Arial, Helvetica, sans-serif; padding:160px; color:#333;line-height:72px;}
div#nav ul#menu2 li a {font:20px Arial, Helvetica, sans-serif;padding:160px;margin-left:160px; color:#333; line-height:72px;}`
jquery:
$(window).scroll(function(e)
{
var location = $(window).scrollTop();
if(location>=$('div#nav').offset().top)
{
$('div#nav').css({'position':'fixed'});
}
});
Upvotes: 0
Views: 144
Reputation: 428
I like to use https://fixedposition.googlecode.com/files/jquery.fixedposition.1.0.0-min.js for this purpose, because this works easy and fine.
First include the .js file in the header of your website, and then use the followig code:
<script>
$(document).scroll(function(){
if( !$('.navbar').length ) return;
if (!$('.navbar').attr('data-top')) {
// If already fixed, then do nothing
if ($('.navbar').hasClass('navbar-fixed')) return;
// Remember top position
var offset = $('.navbar').offset();
$('.navbar').attr('data-top', offset.top);
}
if ($('.navbar').attr('data-top') <= $(this).scrollTop()) {
$('body').addClass('subnav-active');
$('.navbar').addClass('navbar-fixed');
$('#navbarStyleHolder').css("display", "block");
}
else {
$('body').removeClass('subnav-active');
$('.navbar').removeClass('navbar-fixed');
$('#navbarStyleHoler').css("display", "none");
}
});
</script>
Next just go ahead and replace .navbar
with your div in which your nav is in, and then create a .css
class with the formatting your fixed header should have (in my example code called .navbar-fixed
).
This script will automatically replace the .navbar
class with the .navbar-fixed
class when reaching the end of the .navbar
div.
For example if you want to have it on top of the screen, use this css code:
.navbar-fixed {
position:fixed;
top:1;
}
Upvotes: 1