Question

I found several solutions for my problem but I can't get anyone to work. I'm trying to smooth scroll to a tab when a link is clicked. That works perfectly. The problem is that when I have multiple links on a page that points to to a tab, only the link works which have a tab active. So when I click a link and that tab isn't active the link doesn't work.

So what I try to do is to make a tab active when I click a link.

What I have:

<a class="goSmoothly" href="#" data-target="description" onclick="return false">Link to tab1</a>
<a class="goSmoothly" href="#" data-target="specs" onclick="return false">Link to tab2</a>

<ul class="nav-tabs">
  <li class="active"><a href="#description" data-toggle="tab">Tab1</a></li>
  <li><a href="#specs" data-toggle="tab">Tab2</a></li>
</ul>


$( '.goSmoothly' ).on('click', function(event) {
    event.preventDefault();
    var target = "#" + $(this).data('target');

    $('html, body').animate({
      scrollTop: ($(target).offset().top - 150)
    }, 1200);

    var self = $(this), className = "active";
    self.addClass(className).siblings("."+className).removeClass(className);
  });
Was it helpful?

Solution

The problem is this part:

var target = "#" + $(this).data('target');

$('html, body').animate({
  scrollTop: ($(target).offset().top - 150)
}, 1200);

Your $(target) selector is selecting an element with the id attribute of either description or specs, however in your code you have no elements with those IDs. Instead you have elements with those href attributes, which you can select instead using:

var target = $(this).data('target');

$('html, body').animate({
  scrollTop: ($('[href="' + target + '"]').offset().top - 150)
}, 1200);

Also rather than calling:

self.addClass(className).siblings("."+className).removeClass(className);

You can simply:

$('.active').removeClass('active');
$(this).addClass('active');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top