0

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:

  1. This breaks my modals as it references any hashes within a href tag. eg:#myModal link no longer opens.

  2. 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?

Community
  • 1
  • 1
Torads
  • 69
  • 1
  • 10

1 Answers1

0

I was able to fix issue number 1 by adding a mytext in front of the anchors that were being hidden by the navbar and then changing the function to only look for id's starting with that specific text.

 $("a[href*='#mytext']:not([href='#'])").click(function() {

So at this point the only thing not working is the menu collapsing after the anchor link is clicked.

How would I add the below code within the function itself?

$(document).on('click','.navbar-collapse.in',function(e) {
if( $(e.target).is('a') ) {
    $(this).collapse('toggle');
}
});
Torads
  • 69
  • 1
  • 10