Reputation: 45
I want to make a menu that is fixed. But I want it only to be fixed if i've scrolled past it. Actually I want it just like the "how to .." menu on the question ask part of stackoverflow. https://stackoverflow.com/questions/ask
I thought you need jquery to do such things, but i really don't know much about jquery.
I use this code for the menu and i want that to float. So the whole sidebar div needs to float.:
<div id="sidebar">
<div>
<h2 class="title">Sites</h2>
<ul>
<li><a>first li</a></li>
<li><a>second li</a></li>
<li><a>third li</a></li>
</ul>
</div>
<div>
<h2 class="title">Sites</h2>
<ul>
<li><a>first li</a></li>
<li><a>second li</a></li>
<li><a>third li</a></li>
</ul>
</div>
</div>
I know how I can let it float to the top of the page, but i want it to float in a wrapper.
I hope you guys can help me.
EDIT
now i have the floating menu with this code:
<script type="text/javascript">
$(function() {
var offset = $("#sidebar").offset();
var topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
$("#sidebar").stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
$("#sidebar").stop().animate({
marginTop: 0
});
};
});
});
</script>
But there is a really annoying bounce effect when I scroll down. Is there a way to remove that effect?
Upvotes: 0
Views: 1223
Reputation: 2089
In short: You'll bind to the scroll event of the window and check whether the current scrollTop (distance in pixel from the top of the page to the pixel currently at the top of your viewport) is larger than the distance from the top of the page to the top of your sidebar.
If this is given you'll set the difference as marginTop to make the sidebar stay in the visible area.
See at http://css-tricks.com/scrollfollow-sidebar/ for an example and further information.
Upvotes: 2