Open page on specific tab using URL hash
P粉317679342
P粉317679342 2023-09-04 14:33:50
0
1
571
<p>Admittedly I'm a little lost on this since I'm very new to hashes, but I think this might be a solution to my problem so I'm hoping someone here might have some more insight. I have a webpage with multiple "tabs" (a div that hides information until the button is clicked, and a div that hides all other information until the button is clicked) and I want to be able to open to a specific tab from different webpages.< ;/p> <p>This is the skeleton of the previous web page. When you navigate to the page regularly, the first div is visible by default. </p> <pre class="brush:php;toolbar:false;"><div id="first" class="commission"> content </div> <div id="second" class="commission" style="display:none;"> content </div> <div id="third" class="commission" style="display:none;"> content </div></pre> <p>On this page there are buttons that you can click to switch between these divs. </p> <pre class="brush:php;toolbar:false;"><button class="commissiontab" onclick="commissionType(event, 'first')">first</button> <button class="commissiontab" onclick="commissionType(event, 'second')">Second</button> <button class="commissiontab" onclick="commissionType(event, 'third')">Third</button></pre> <p>The javascript to switch between these is: </p> <pre class="brush:php;toolbar:false;">function commissionType(evt, commissionName) { var i,commissiontab; var x = document.getElementsByClassName("commission"); for (i = 0; i < x.length; i ) { x[i].style.display = "none"; } commissiontab = document.getElementsByClassName("commissiontab"); for (i = 0; i < x.length; i ) { commissiontab[i].className = commissiontab[i].className.replace(" selected", ""); } window.scrollTo({ top: 0, behavior: 'smooth' }); evt.currentTarget.className = " selected"; document.getElementById(commissionName).style.display = "grid"; }</pre> <p>Somehow I want to have these buttons on a different page ("index.html"), but when you click on the "third" you are taken to a new page ("commissiontypes.html") "Third" instead of the default "First". </p> <p>If there are other solutions besides using hashes, I'd love to hear about it, thanks for taking a closer look. </p>
P粉317679342
P粉317679342

reply all(1)
P粉492959599

You can initially hide all elements using the 'commission' class and then show only one of them when the page loads based on location.hash. This way, commissiontypes.html (and commissiontypes.html#first) will show the first div, commissiontypes.html#second will show the second div, etc.

document.querySelectorAll('.commission').forEach(x => x.style.display = 'none');
const activeEl = document.querySelector(location.hash || '#first');
activeEl.style.display = '';

(Alternatively, you may also consider using query parameters to indicate this section.)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template