Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to id with fixed top bar

My page has a fixed top navigation bar an several id-elements on page. if i press a link one of these id-elements, it scrolls this id to top, but its hidden under the top navigation bar. In the wild the page is very long and has diffent "jumppoints".

I have a simplified fiddle to show the problem with the following html

<div id="fixedbar">This is the fixed top bar</div>
<div id="toplinks"><a href="#first">First</a> <a href="#second">Second</a></div>
<p id="first"><strong>First</strong>
    Lorem ipsum dolor sit amet[...]
</p>
<p id="second"><strong>Second</strong>
    Duis autem vel eum iriure dolor[...]
</p>
<div id="bottomlinks"><a href="#first">First</a> <a href="#second">Second</a></div>

and this css

body{padding:0;margin:0}
#toplinks{padding-top:2em}
#fixedbar{
    position:fixed;
    background-color:#ccc;
    height:2em;
    width:100%
}

I want that a click on a link scrolls to the right element but complements the fixed navigation bar. A possible solution should at best only include css, but can include javascript or jquery (1.9 is used production).

Thank you for any help!

like image 900
Bastian Rang Avatar asked Feb 28 '13 15:02

Bastian Rang


2 Answers

Here is the JavaScript work around for this problem. Bind a click event to the <a> in toplinks and bottomlinks, on the click event find target <p> offset and scroll to it by using javascript.

$("#toplinks, #bottomlinks").on('click','a', function(event){ 
    event.preventDefault();
    var o =  $( $(this).attr("href") ).offset();   
    var sT = o.top - $("#fixedbar").outerHeight(true); // get the fixedbar height
    // compute the correct offset and scroll to it.
    window.scrollTo(0,sT);
});

Fiddle : http://jsfiddle.net/AnmJY/1/

like image 127
Derek Avatar answered Nov 03 '22 01:11

Derek


Modified JS:

 $("#toplinks a").click(function() {
    var id =  $(this).attr('href');
     $('html, body').animate({         
         scrollTop: $(id).offset().top-40
     }, 1000);
 });

Modified CSS:

body{padding:0;margin:0}
#toplinks{padding-top:2em}
#fixedbar{
    position:fixed;
    background-color:#ccc;
    height:40px;
    width:100%
}

Fiddle: http://jsfiddle.net/xSdKr/

40(px) is the menu height, 1000 is time in miliseconds to perform an animation.

JS solution is by far more elegant than pure CSS mostly because it keeps elements in place without any artificial paddings that might interfere with your website styles. It also includes animation - people usually finds smooth transitions much more acceptable than insta-flips with pure CSS/HTML as they make it easier to follow the content of the page and where you exactly are. Downside is that if someone uses #first in URL - he will see the menu overlapping with headers.

like image 24
MarcinWolny Avatar answered Nov 02 '22 23:11

MarcinWolny