StudentX
StudentX

Reputation: 2323

Smooth scrolling javascript code messing with Bootstrap Tab code

I have the following code to enable smooth scrolling for on page navigation which I simply copy-pasted from somewhere I do not remember. Since the smooth scrolling happens on an anchor tags click, it messes up Bootstrap Javascript for Tab which too utilizes anchor tags(This is what I have concluded, I hope I am correct).

$(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
            }, 1000);
            return false;
        }
    }
});
});

Now I do not understand this $('a[href*="#"]:not([href="#"])') part of the code, can somebody please put some light on what this is doing ? Also how do I fix this so that the above function fires only on On Page anchor clicks ?

Upvotes: 0

Views: 131

Answers (1)

priya_singh
priya_singh

Reputation: 2488

a[href*="#"]:not([href="#"])

Above selector is gone target a tag with href="#smthing". So by default its gone effect bootstrap tab functionality.

Instead of that increase css specificity. Use parent class like

 $(function() {
  $('.myParent 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
        }, 1000);
        return false;
      }
   }
 });
});

Upvotes: 1

Related Questions