From dedd80bebe962ebb3aed3c8bdda9c5c44bfe129c Mon Sep 17 00:00:00 2001 From: Anthony Veaudry Date: Fri, 24 Nov 2023 16:28:17 +0200 Subject: [PATCH] Give the option for tabs not to scroll the browser --- src/tabs.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/tabs.js b/src/tabs.js index 81cb661..eec1f6a 100644 --- a/src/tabs.js +++ b/src/tabs.js @@ -5,7 +5,8 @@ export default class extends Controller { static targets = ['tab', 'panel', 'select'] static values = { index: 0, - updateAnchor: Boolean + updateAnchor: Boolean, + scrollToAnchor: Boolean, } connect() { @@ -56,7 +57,14 @@ export default class extends Controller { // Update URL with the tab ID if it has one // This will be automatically selected on page load if (this.updateAnchorValue) { - location.hash = this.tabTargets[this.indexValue].id + const new_tab_id = this.tabTargets[this.indexValue].id // Grab the id from the newly activated tab + if (this.scrollToAnchorValue){ + location.hash = new_tab_id // Use location.hash to change the URL with scrolling + } else { + const currentUrl = window.location.href // Get the current URL + const newUrl = currentUrl.split('#')[0] + '#' + new_tab_id // Create a new URL with the updated ID + history.replaceState({}, document.title, newUrl) // Use history.replaceState to change the URL without scrolling + } } }