This solved many issues I was having with Scrollspy and Bootstrap navbar.
V2 adds some perhaps redundant code but it clears out a funky navbar flicker that I noticed on chrome. This new version also works well with a top and bottom nav.
/** First portion from http://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header
* or http://jsfiddle.net/ianclark001/aShQL/
*Works for anchor tags in gerneal - doesn't relate to scrollspy
* Check a href for an anchor. If exists, and in document, scroll to it.
* If href argument ommited, assumes context (this) is HTML Element,
* which will be the case when invoked by jQuery after an event
*/
function scroll_if_anchor(href) {
href = typeof(href) == "string" ? href : $(this).attr("href");
// You could easily calculate this dynamically if you prefer
var fromTop = 56;
// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
// Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
if(href.indexOf("#") === 0) {
var $target = $(href);
// Older browser without pushState might flicker here, as they momentarily
// jump to the wrong position (IE < 10)
if($target.length) {
$('html, body').animate({ scrollTop: $target.offset().top - fromTop });
if(history && "pushState" in history) {
history.pushState({}, document.title, window.location.pathname + href);
return false;
}
}
}
}
// When our page loads, check to see if it contains and anchor
scroll_if_anchor(window.location.hash);
// Intercept all anchor clicks
$("body").on("click", "a", scroll_if_anchor);
// Hides navbar-collapse after click
$('.nav a').click(function(){
$('.navbar-collapse').collapse('hide');
});
/** New section - specific js to enhance scrollspy functionality
* from https://jsfiddle.net/mekwall/up4nu/
* Cache selectors
*/
var lastId,
topMenu = $("#myScrollspy"),
topMenuHeight = topMenu.outerHeight() + 32,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.