Sackadelic
Sackadelic

Reputation: 1019

Clicking a Bootstrap Nav Tab won't scroll to Tab Pane - jQuery / Bootstrap

I have some Bootstrap vertical tabs that I'm struggling with what I felt like would be a simple operation.

Goal:

On the click of Tab, I want to smooth-scroll to the corresponding pane.

What's Actually Happening:

On click of the tab, the browser animates to the tab, not the tab pane. I've tried passing in the paneId instead of the ID, but that doesn't work at all. Any idea where I'm going wrong?

Codepen:

Here's a Codepen: Codepen!

jQuery:

$("#tabs .nav-link").click(function (e) { //on click of nav tav, perform this:
    var id = $(e.target).prop("id"); //Grab ID of .nav-link clicked
    var paneId = id.replace("tab", "pane"); //Replace "tab" with "pane" and assign new var

    function navigateToElement(id) {
        $("html, body").animate(
            {
                scrollTop: $("#" + id).offset().top
            },
            300
        );
    }
    navigateToElement(id); //Tried with "paneId" instead of "id" to scroll to the pane, but doesn't work
});

Any idea where I'm going wrong?

Upvotes: 0

Views: 313

Answers (2)

Sackadelic
Sackadelic

Reputation: 1019

I just realized that it doesn't matter what pane I scroll to, as bootstrap will display the panes under #panes. As long as I can scroll to that, I'm good. This code worked:

$("#tabs .nav-link").click(function (e) {
    var target = $("#panes");

    $([document.documentElement, document.body]).animate(
      {
        scrollTop: $(target).offset().top - 20, // added a bit of offset
      },
      350
    );
  });

Upvotes: 0

Kinglish
Kinglish

Reputation: 23654

This line:

var paneId = id.replace("tab", "pane"); //Replace "tab" with "pane" and assign new var

Is creating a variable like: v-pills-profile-pane and there isn't a div on the page with that id. I did see a div with id="v-pills-profile". Change that last line to this and it should work:

var paneId = id.replace("-tab", "");

Upvotes: 1

Related Questions