Search code examples
javascriptjquerycsstwitter-bootstrap

links to #anchors in navbar not closing after clicked


I had previously solved issue where my navbar links weren't collapsing after being clicked and thanks to @Kami I had this working using the below code

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

from Bootstrap 3 after navbar collapse, toggle wont reopen nav

but when I added this nice function below to keep the navbar from overlapping content it broke.

What part of this function caused the above to break and how can I implement both?

  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*='#JDG']: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;
  }
}


});

Using @Shouvik suggestion from offsetting an html anchor to adjust for fixed header I changed one line of code to only look for anchors that started with #JDG as without this links to anchors to my modal windows broke. You can see what is happening here where my services menu items wont close after being clicked. the functions are placed at the end of the bootstrap.min.js file


Solution

  • Jasper pointed out the issue why these weren't working when together.

    I just had to remove the

    return false;
    

    from both functions.