Простая версия - посетите любой /state/index.html и состояние запоминается в localStorage
Вы включаете JS на каждой странице (используя внешний файл JS), где у вас есть дом URL - ссылка требует id="home"
Скрипт предполагает, что у вас ВСЕГДА yourserver.com/state/index.html
Если вам не нужно менять троичный
let state = parts.length === 3 ? parts[1] : "";
Вот код, который нужно скопировать
window.addEventListener("load", function() { // when page loads
const url = new URL(location.href);
const parts = url.pathname.split("/"); // creates ["","page.html"] OR ["","state","index.html"]
let state = parts.length === 3 ? parts[1] : ""; // get the state from the URL OR
if (state === "") { // get the state from localStorage instead
state = localStorage.getItem("state") || "";
}
if (state) { // do we NOW have a state?
localStorage.setItem("state",state);
url.pathname = state ? "/"+state+"/index.html" : "/index.html";
[...document.querySelectorAll(".home")].forEach(lnk => lnk.href = url);
}
})
Поскольку стековые склипы не поддерживают localStorage, вам нужно раскомментировать и удалить строки при копировании кода на сервер.
window.addEventListener("load", function() { // when page loads
// const url = new URL(location.href); // uncomment on your server
const url = new URL("https://yourserver.com/florida/index.html"); // remove when on your server
const parts = url.pathname.split("/"); // creates ["","page.html"] OR ["","state","index.html"]
console.log(parts)
let state = parts.length === 3 ? parts[1] : ""; // get the state from the URL OR
if (state === "") { // get the state from localStorage instead
// state = localStorage.getItem("state") || ""; // uncomment on your server
}
if (state) { // do we NOW have a state?
// localStorage.setItem("state",state); // uncomment on your server
url.pathname = state ? "/"+state+"/index.html" : "/index.html";
[...document.querySelectorAll(".home")].forEach(lnk => lnk.href = url);
}
})
<a id="home" href="index.html">Home</a>
Полный пример
Приведенный ниже код выполняет следующие действия:
- устанавливает активную страницу на основе URL, так вам нужно сопоставить примерно с - регистрозависимый
- устанавливает состояние из localStorage, если уже установлено до
- устанавливает состояние из выпадающего списка. Это может перезагрузить страницу при необходимости
window.addEventListener("load", function() { // when page loads
// const url = new URL(location.href); // uncomment on your server
const url = new URL("https://yourserver.com/tutorials"); // remove when on your server
const ul = document.getElementById("links");
// let state = localStorage.getItem("state") || ""; // uncomment on your server
let state = "FLORIDA"; // remove from code on your server
// state selection
const stateSel = document.getElementById("stateSel");
if (state) { // already have a state
stateSel.value=state;
}
stateSel.onchange=function() { // using onchange to trigger later
state = this.value;
// localStorage.setItem("state",state); // uncomment on your server
[...document.querySelectorAll(".home")].forEach(lnk => lnk.href = url);
};
stateSel.onchange(); // set the link when loading page
// active link
[...ul.querySelectorAll("li")].forEach(function(li) {
const page = li.getAttribute("data-page");
li.querySelector("a").classList.toggle("active", url.pathname.indexOf(page) != -1); // set active
})
})
/* from https://css-snippets.com/simple-horizontal-navigation/ */
.nav ul {
list-style: none;
background-color: #444;
text-align: center;
padding: 0;
margin: 0;
}
.nav li {
font-family: 'Oswald', sans-serif;
font-size: 1.2em;
line-height: 40px;
height: 40px;
border-bottom: 1px solid #888;
}
.nav a {
text-decoration: none;
color: #fff;
display: block;
transition: .3s background-color;
}
.nav a:hover {
background-color: #005f5f;
}
.nav a.active {
background-color: #fff;
color: #444;
cursor: default;
}
@media screen and (min-width: 600px) {
.nav li {
width: 120px;
border-bottom: none;
height: 50px;
line-height: 50px;
font-size: 1.4em;
}
<div class="nav">
<ul id="links">
<li data-page="/index"><a id="home" href="index">Home</a></li>
<li data-page="/tutorials"><a href="tutorials">Tutorials</a></li>
<li data-page="/about"><a href="about">About</a></li>
<li data-page="/news"><a href="news">Newsletter</a></li>
<li data-page="/contact"><a href="contact">Contact</a></li>
</ul>
</div>
<select id="stateSel">
<option value="">Which state?</option>
<option value="FLORIDA">Florida</option>
<option value="NEVADA">Nevada</option>
</select>