简体   繁体   中英

How to navigate to a new bootstap 4 tab on the same page from a sidebar link?

I'm unable to get sidebar links to navigate to bootstrap 4 tabs on the center page using this technique . Here is the javascript in my _SidebarLayout.cshtml :

<script>
    function selectTabNamedInUrlHash() {
        let selectedTab = window.location.hash;
        $('.nav-link[href="' + selectedTab + '"]').trigger('click');
    }

    jQuery(document).ready(function ($) {
        selectTabNamedInUrlHash();
    })
</script>

A sidebar anchor links to the page and adds a fragment (hash) to the href of the tab I want to navigate to (url end: SPC#SpcFilm). The sidebar link also calls the above function.

<a onclick="selectTabNamedInUrlHash();" asp-page="/SPC/Index" asp-fragment="SpcFilm">Film</a>

On Index.cshtml the Bootstrap 4 tab is identified by href="#SpcFilm" This solution works when navigating to a new page, but it's not working when navigating to another tab on the same page.

I'm answering my own question here with the help of a coworker. Use the hashchange event of modern browsers (which is recognized by jQuery) to select the tab. In Bootstrap 4 tabs are activated using data-toggle="tab" or data-toggle="pill" . So the only script needed is:

<script>
    $(window).on('hashchange ready', function () {
        let selectedTab = window.location.hash;
        $('a[href="' + selectedTab + '"][data-toggle="tab"]').trigger('click');
    });
</script>

Each sidebar link contains a hash matching a desired tab's href. When the sidebar link is clicked the jQuery above triggers a click on the tab thus opening the tab on the page.

Note: Be sure to remove onclick="selectTabNamedInUrlHash();" from the sidebar links and remove the corresponding function as it is no longer needed and may interfere with the solution.

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