Open page on specific tab using URL hash
P粉317679342
2023-09-04 14:33:50
<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>
You can initially hide all elements using the
'commission'
class and then show only one of them when the page loads based onlocation.hash
. This way, commissiontypes.html (and commissiontypes.html#first) will show the first div, commissiontypes.html#second will show the second div, etc.(Alternatively, you may also consider using query parameters to indicate this section.)