Home >Web Front-end >JS Tutorial >How Do I Programmatically Navigate to Specific Bootstrap Tabs via URL?

How Do I Programmatically Navigate to Specific Bootstrap Tabs via URL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 19:30:12445browse

How Do I Programmatically Navigate to Specific Bootstrap Tabs via URL?

Navigating to Specific Tabs in Bootstrap

When working with Bootstrap tabs, you may encounter the challenge of linking directly to a specific tab from an external source. This can be an inconvenience if you want users to seamlessly access the desired tab from external links. Here's how to solve this issue:

To enable links directly to tabs, implement the following JavaScript solution:

// Enable link to tab
var hash = location.hash.replace(/^#/, '');
if (hash) {
    $('.nav-tabs a[href="#' + hash + '"]').tab('show');
}

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

With this script in place, clicking on external links like these:

<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>

now navigates users directly to the Home and Notes tabs, respectively. Additionally, when a tab is selected within the page, the URL's hash changes accordingly, persisting the tab selection even after page reloads.

The above is the detailed content of How Do I Programmatically Navigate to Specific Bootstrap Tabs via URL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn