When scrollbar is on top browser displays:
HTML:
-------------------------
| HEADER |
-------------------------
| NAVBAR |
-------------------------
| body |
-------------------------
When scrollbar is down NOW browser normally displays:
HTML:
-------------------------
| |
| body |
| |
-------------------------
But I'd like to have:
-------------------------
| NAVBAR |
-------------------------
| |
| body |
| |
-------------------------
I tried with:
<div id="navbar">...</div>
CSS:
#navbar {
position:fixed;
z-index:1;
}
But this only works if navbar is on the top position. I have the header on top...
DEMO
I have used an image at top instead of the "HEADER" mentioned in your question.
This is the js I have used to make the header(navbar in your case) fixed.
var stickyNavTop = $('#header').offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() > stickyNavTop) {
$('#header').addClass('fixed');
}
else {
$('#header').removeClass('fixed');
}
});
A potential solution or class of solutions is called an Affix.
See boostrap's example here:
http://getbootstrap.com/javascript/#affix
The general strategy is to watch how close something is to the top of the window, and THEN make its CSS position: fixed
like you tried to do.
This can be trickier than expected to implement on your own when it comes to 'unsticking' the element, as you need to track where it came from originally.
Here's an example taken from html5rocks which works nice.
<style>
.sticky {
position: fixed;
top: 0;
}
.header {
width: 100%;
background: #F6D565;
padding: 25px 0;
}
</style>
<div class="header"></div>
<script>
var header = document.querySelector('.header');
var origOffsetY = header.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? header.classList.add('sticky') :
header.classList.remove('sticky');
}
document.addEventListener('scroll', onScroll);
</script>
For further reading: http://updates.html5rocks.com/2012/08/Stick-your-landings-position-sticky-lands-in-WebKit
Of course, .header
here is your NAVBAR.
You will tell #navbar where it should be fixed. Use the css properties top, left, bottom, right. In your case you only need laft top right set to 0 and a fixed height, for example 30px.