简体   繁体   中英

Bootsrap Twitter tabs - go a specific tab when the page reloads

I am developing an web app. In some of the web pages I am using Twitter Bootstrap pane tabs. below is my code.

I am trying to go to a specific tab when the page reloads. For example: when I am in the www.mywebsite.com/c.html the first active tab is 'bc' when I go to 'cc' and refresh the page it goes back to 'bc'. I want it to stay in 'cc'. I need to be able to do something like this www.mywebsite.com/c.html#cc But this does not work.

I looked at Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload? but could not find an answer that fits my code. I tried changing the class names still no luck.

<div class="wp">
    <div class="widget">
        <div class="tabs">
            <ul class="nav nav-pills nav-justified">
                <li class="active"><a href="#bc" data-toggle="tab">bc</a></li>
                <li><a href="#cc" data-toggle="tab">cc</a></li>
                <li><a href="#lc" data-toggle="tab">lc</a></li>
                <li><a href="#pc" data-toggle="tab">pc</a></li>
                <li><a href="#sc" data-toggle="tab">sc</a></li>                                        
            </ul>
        </div>
    </div>
</div>
<div class="tab-content tab-content-inverse">
    <div class="tab-pane active" id="bc">
        ...
    </div>
    <div class="tab-pane" id="cc">
        ...
    </div>
    <div class="tab-pane" id="lc">
        ...
    </div>
    <div class="tab-pane" id="pc">
        ...
    </div>
    <div class="tab-pane" id="sc">
        ...
    </div>
</div>

Get the anchor part of the URL by using location.hash in your JavaScript/jQuery.

Then, append it into the following JavaScript:

document.querySelector('.nav li a[href="#lc"]').click();

You'll simply insert the value you pull using location.hash after the href= portion, which will then be clicked.

Change the value in the following Bootply example and run it to see how it works.

BOOTPLY

You can write some code in JavaScript that will run when the page loads and check the # part of the url ( window.location.hash ). Take a look at the bootstrap website for how to toggle a certain tab: http://getbootstrap.com/javascript/#tabs

This worked for me. I changed the class names to tabs and the event to click event

 $(document).ready(function () {               
            var hash = document.location.hash;
            var prefix = "tab_";
            if (hash) {
                $('.tabs a[href=' + hash.replace(prefix, "") + ']').tab('show');
            }
            $('.tabs a').on('click', function (e) {                    
                window.location.hash = e.target.hash.replace("#", "#" + prefix);
            });
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM