Home > Web Front-end > JS Tutorial > How Can I Target Specific Bootstrap Tabs Using External Links and Preserve the Selection on Reload?

How Can I Target Specific Bootstrap Tabs Using External Links and Preserve the Selection on Reload?

Barbara Streisand
Release: 2024-12-03 03:59:11
Original
975 people have browsed it

How Can I Target Specific Bootstrap Tabs Using External Links and Preserve the Selection on Reload?

Targeting Specific Bootstrap Tabs with External Links

Query:

How can I navigate to a specific Bootstrap tab when clicking on an external link, ensuring the desired tab remains active upon page reload?

Answer:

To achieve this functionality, implement the following JavaScript code:

// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, '');  // ^ means starting, meaning only match the first hash
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;
})
Copy after login

Explanation:

  1. Locating the hash: Retrieve the hash (part following the "#") from the current URL.
  2. Activating the tab: Search for a tab link that matches the hash and toggle it to show.
  3. Preserving the hash on reload: Update the URL hash when a tab is shown to maintain its active status upon page reload.

The above is the detailed content of How Can I Target Specific Bootstrap Tabs Using External Links and Preserve the Selection on Reload?. 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