To attach the tabs link to the URL and maintain the selected tab when the page is refreshed, you can use JavaScript and the URL hash.
First, add an event listener to the tabs links to handle the click event and update the URL hash with the corresponding tab ID. Then, on page load, check if there is a hash in the URL and activate the corresponding tab.
Here's an example of how you can achieve this:
// Get all the tab links
const tabLinks = document.querySelectorAll('#myTab a');
// Add click event listener to each tab link
tabLinks.forEach(tabLink => {
tabLink.addEventListener('click', (event) => {
// Prevent the default link behavior
event.preventDefault();
// Get the target tab ID from the data attribute
const targetTab = tabLink.getAttribute('data-tabs-target');
// Update the URL hash with the target tab ID
window.location.hash = targetTab;
// Activate the selected tab
activateTab(targetTab);
});
});
// Check if there is a hash in the URL on page load
window.addEventListener('DOMContentLoaded', () => {
const hash = window.location.hash;
// Activate the tab based on the hash
if (hash) {
activateTab(hash);
}
});
// Function to activate the selected tab
function activateTab(tabId) {
// Get all the tab content elements
const tabContents = document.querySelectorAll('.tab-content');
// Deactivate all tab links and tab contents
tabLinks.forEach(tabLink => {
tabLink.setAttribute('aria-selected', 'false');
});
tabContents.forEach(tabContent => {
tabContent.classList.remove('active');
});
// Activate the selected tab link and tab content
const selectedTabLink = document.querySelector(`[data-tabs-target="${tabId}"]`);
const selectedTabContent = document.querySelector(tabId);
selectedTabLink.setAttribute('aria-selected', 'true');
selectedTabContent.classList.add('active');
}
Make sure to add the active class to the corresponding tab content element to show it as active.
Note: This solution assumes that you have a CSS class named active to style the active tab content. You may need to adjust the code and CSS classes based on your specific implementation.