Home > Web Front-end > JS Tutorial > body text

How to Navigate Directly to a Bootstrap Tab on Page Reload or via External Link?

Barbara Streisand
Release: 2024-11-26 16:42:14
Original
191 people have browsed it

How to Navigate Directly to a Bootstrap Tab on Page Reload or via External Link?

Navigate Directly to Bootstrap Tab on Page Reload or External Link

When working with Bootstrap Tabs in a web application, users may encounter the need to navigate directly to a specific tab when the page initially loads or when clicked from an external link.

Problem:

Consider the following HTML code:

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

The intent is for the links to navigate to the respective Home and Notes tabs when clicked from an external page.

Solution:

To achieve this functionality, you can utilize the following JavaScript code:

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

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

This code performs the following actions:

  • Enable link to tab: When the page loads, the code identifies the hash portion of the URL (#home or #notes) and automatically activates the corresponding tab in the navigation bar.
  • Change hash for page-reload: When a user navigates between tabs, the code updates the hash in the URL to reflect the selected tab. This way, when the page is reloaded, it automatically navigates to the correct tab.

The above is the detailed content of How to Navigate Directly to a Bootstrap Tab on Page Reload or via External Link?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template