I was having a problem with my anchor links being hidden under the fixed-top navbar in bootstrap 3 and I love the solution that Shouvik suggested here:
offsetting an html anchor to adjust for fixed header
However while the below code solves that issue perfectly, it breaks a few others.
function scrollToAnchor() {
if($(".jquery-anchor").length > 0 && document.URL.indexOf("#") >= 0){
var anchor = document.URL.split("#")[1];
$(".jquery-anchor").each(function() {
if($(this).attr("name") == anchor) {
$("html,body").animate({
scrollTop: $(this).offset().top - 50},
'slow');
}
});
}
}
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 30 //offsets for fixed header
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 30 //offset height of header here too.
}, 1000);
return false;
}
}
});
Two issues come up when I use this code:
This breaks my modals as it references any hashes within a href tag. eg:#myModal link no longer opens.
When in mobile view it no longer closes the menu after clicking the link. This problem was originally solved by the below script which no longer works when I implemented the above.
$(document).on('click','.navbar-collapse.in',function(e) { if( $(e.target).is('a') ) { $(this).collapse('toggle'); } });
So my question is: How can I still use this code and keep it from breaking my modals while also making the menu collapse after the anchor tag is clicked while in mobile view?
Can I have the above code ignore my specific modal anchor links?