I've got some code which has three page tabs, only one is shown at a time, with an active marker too however I cannot work out how I can link directly to the url
https://jsfiddle.net/c51xvekh/
My current html is:
<div >
<ul >
<li><a id="sunbed-tab" onclick="openTabs(event, 'sunbed')">Sunbed<br>Packages</a></li>
<li><a id="trainer-tab" onclick="openTabs(event, 'trainer')">Personal<br>Trainers</a></li>
<li><a id="sauna-tab" onclick="openTabs(event, 'sauna')">Sauna<br>Rooms</a></li>
</ul>
</div>
<div id="sunbed" >
This is sunbed page
</div>
<div id="trainer" >
This is trainer page
</div>
<div id="sauna" >
This is sauna page
</div>
The js is
function openTabs(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("city");
for (i = 0; i < tabcontent.length; i ) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i ) {
tablinks[i].classList.remove("active");
}
document.getElementById(tabName).style.display = "block";
document.getElementById(tabName "-tab").classList.add("active");
}
document.getElementById("sunbed-tab").click();
for example - if I visit url.com/page#sauna then it opens the page with the sauna section opened and likewise for trainers if /page#trainer is visited.
Is there something in the JS that could do this?
I've just tried
if(window.location.hash.substring(1)=='trainer') {
document.getElementById("trainer-tab").click();
} elseif(window.location.hash.substring(1)=='sauna') {
document.getElementById("sauna-tab").click();
} else {
document.getElementById("sunbed-tab").click();
}
but it seems to fail with unexpected token.
(I'm a php dev and newly learning js)
I've tried running :target in the CSS and having it set to display: block but that didnt work.
Any ideas please?
CodePudding user response:
Could use #hash or QueryParams. I've attached an example using both
//USING #HASH
let hashString = location.hash ? location.hash.substring(1) : "";
if(hashString) {
openTabs(null, hashString);
}
//USING ?QUERY=PARAM
let queryParams = new URLSearchParams(location.search);
if(queryParams.get('tab')) {
openTabs(null, queryParams.get('tab'));
}
CodePudding user response:
You could try get url location by splitting hash:
const location = window.location.href.split("#")[1];
Then, set city class to display:none and add city--sunbed and so on, you've to check if elements contains that class e.g:
const tabsHandler = document.querySelectorAll('.city');
tabsHandler.forEach((element)=>{
element.classList.contains(`city--${location}`) ? element.classList.add('show-block') : '';
});