Skip to content

Instantly share code, notes, and snippets.

@ivos
Forked from claudiodangelis/fixNavbarIssue.js
Created November 11, 2012 18:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivos/4055810 to your computer and use it in GitHub Desktop.
Save ivos/4055810 to your computer and use it in GitHub Desktop.
[bootstrap] fixing issue #4153 `navbar-fixed-top`
function fixNavbarIssue(){
/* Quick & dirt draft fix for the bootstrap's navbar-fixed-top issue.
Overview
When you call a given section of a document (e.g. via <a href="#section"> or domain.com/page#section1) browsers show that section at the top of window. Bootstrap's navbar-fixed-top, _since it's fixed_, *overlays* first lines of content.
This function catches all of the <a> tags pointing to a section of the page and rewrites them to properly display content.
Works fine even if a # section is called from URL.
Usage
Paste this function wherever you want in your document and append _fixNavbarIssue()_ to your <body>'s onload attribute.
*/
if($(document).width()>979){ // Required if "viewport" content is "width=device-width, initial-scale=1.0": navbar is not fixed on lower widths.
var hash = window.location.hash;
// Code below fixes the issue if you land directly onto a page section (http://domain/page.html#section1)
if(hash!=""){
$(document).scrollTop(($(hash).offset().top) - $(".navbar-fixed-top").height());
}
// Here's the fix, if any <a> element points to a page section an offset function is called
var locationHref = window.location.protocol + '//' + window.location.host + $(window.location).attr('pathname');
var anchorsList = $('a').get();
for(i=0;i<anchorsList.length;i++){
var hash = anchorsList[i].href.replace(locationHref,'');
if (hash[0] == "#" && hash != "#"){
var originalOnClick = anchorsList[i].onclick; // Retain your pre-defined onClick functions
setNewOnClick(originalOnClick,hash);
}
}
}
function setNewOnClick(originalOnClick,hash){
anchorsList[i].onclick=function(){
$(originalOnClick);
$(document).scrollTop(($(hash).offset().top) - $(".navbar-fixed-top").height());
return false;
};
}
}
@tlongren
Copy link

Is doing this still necessary? I'm having all sorts of trouble with scrollspy and navbar-fixed-top. Covering the top of the section. And not giving the nav element the "active" class relative to that section. Instead the nav element prior to the current section has the active class.

Any advice?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment