0

I want to return the user to content that was reached by accessing a dropdown link from a bootstrap pill menu.

This question is similar to this one - but the wrinkle is that that solution does not work when the link is in a dropdown menu.

I have koppor's solution working fine as it relates to the pills themselves, but I'm stumped how to return to the same view after refresh when the content is accessed from the dropdown.

Specifically, when you navigate to the 'xxx' or 'yyy' content from the "Misc" menu, then refresh the page, the page defaults to the "home" content (even though the 'Misc' pill is still active).

<ul class="nav nav-pills" id="myTab">
    <li class="active"><a href="#home">Home</a></li>
    <li><a href="#profile">Profile</a></li>
    <li class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#misc">Misc<span class="caret"></span></a>
    <ul class="dropdown-menu">
    <li><a class="dropdown-toggle" href="#more_x" data-toggle="pill">xxx</a></li>
    <li><a class="dropdown-toggle" href="#more_y" data-toggle="pill">yyy</a></li>
    </ul>
</li>
<li><a href="#messages">Messages</a></li>
    <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
    <div class="tab-pane active" id="home">home</div>
    <div class="tab-pane" id="profile">profile</div>
    <div class="tab-pane" id="more_x">more info x</div>
    <div class="tab-pane" id="more_y">more info y</div>
    <div class="tab-pane" id="messages">messages</div>
    <div class="tab-pane" id="settings">settings</div>
</div>

<script>
    $('#myTab a').click(function (e) {
        e.preventDefault()
        $(this).tab('show')
    });

    // store the currently selected tab in the hash value
    $("ul.nav-pills > li > a").on("shown.bs.tab", function (e) {
       var id = $(e.target).attr("href").substr(1);
       window.location.hash = id;
    });

    // on load of the page: switch to the currently selected tab
    var hash = window.location.hash;
    $('#myTab a[href="' + hash + '"]').tab('show');
</script>

Any/all suggestions welcomed!

Community
  • 1
  • 1
globalSchmidt
  • 1,329
  • 16
  • 28

1 Answers1

1

I had a similar issue. What I did was create a hidden tab. When the page loads go to that tab first then load the tab you really want to load (what is in your hash).

Edit: I was thinking of it differently. Try changing your script to this. It should set window.location.hash to the active tab whenever one is clicked.

$('#myTab a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
    window.location.hash = $(this).attr("href");

});


// on load of the page: switch to the currently selected tab
var hash = window.location.hash;

$('#myTab a[href="' + hash + '"]').tab('show');
Matt H
  • 205
  • 2
  • 8