I have a website with a floating title bar. (code below) I have fixed the problem you expect me to be asking about, but I still have another one.
A common problem is when you click on an link to an anchor within the page, the title bar covers up the desired destination, anchor #part2
. This is a known problem with lots of solutions. (e.g. This stack question) My solution was to simply move the anchor up. That works but
- If you paste the http://server/page.html#part2 link into the browser location bar, it works.
- If you click on the link to the anchor within the page, the offset is not honoured. I believe it is because When we click on the
#part2
link, the browser says "Ok, I've got to scroll down to#part2
. Let me computer where #part2 is. It's at y=1,200 pixels." (made up number). But then when the scroll starts, the floating header div element is floated out to relative positioning and the 1,200 pixel count overshoots.
Please see full example here: https://jsfiddle.net/smorton/7p431smr/
I suspect that my solutions are to find another way to float the title bar, or to find some way to have the page offset recalculated in the scroll()
function. But I need help with either of these, or an alternate solution.
Update
I wasn't explicit, but it is important to me that the floating title bar is not at the top of the page when the page is scrolled to the top. Just like in my jsfiddle example. Imagine that this Stack page looked like normal at the top, but when you scrolled down a small bar saying "HTML + JS - variation on the floating titlebar and link to named anchor bug" followed you down. The solutions provided so far, I believe, rely on putting the title bar at the very top, which is not what I'm looking for.
Solution
Ok, in the end I just put another div around the header bar of fixed 40px height so that even when the header bar is popped out, that 40px remains reserved.
html:
<div id=header_placeholder>
<div id=floatbar class=header> This is the header bar<br>It will follow as you scroll</div>
</div>
css:
#header_placeholder {height: 40px;}
Floating title bar jquery 1.11 code: (please prefer jsfiddle link)
$(window).scroll(function(){
if ($(window).scrollTop() >= 100)
{
$("#floatbar").css({position:'fixed',top:'0'});
$(".summary").css({margin: '0'});
}
else
{
$("#floatbar").css({position: 'relative'});
$(".summary").css({margin: '8 px 0'});
}
});