I am making a website with the option to change languages. Every time when you refresh the page though, the language you selected returns to the original language. The code below shows the html and JavaScript code for how this function works:
const langEl = [...document.querySelectorAll(".lang")];
const textEl = document.querySelector(".text");
let chosenLanguage = 'NL';
langEl.forEach((el) => {
el.addEventListener("click", () => {
langEl.map(item => item.classList.contains("active") ? item.classList.remove("active") : false);
el.classList.add("active");
chosenLanguage = el.innerText;
const attr = el.getAttribute("language");
textEl.textContent = data[attr].text;
});
});
var data = {
dutch: {
text: "test test"
},
english: {
text: "test test"
},
spanish: {
text: "prueba prueba"
},
indonesian: {
text: "tes tes"
}
};
:root {
--secondary-color: #4978ff;
}
.language {
background: #141414;
text-align: center;
padding: 60px 0 50px;
}
.language a {
margin: 0;
text-transform: uppercase;
color: #fff;
text-decoration: none;
padding: 0 15px;
font-weight: bold;
background: #555656;
font-size: 18px;
}
.language a.active {
background: var(--secondary-color);
}
<p class="text">test test</p>
<div class="language">
<div class="langWrap">
<a href="#" language='dutch' class="lang active">NL</a>
<a href="#" language='english' class="lang">EN</a>
<a href="#" language='spanish' class="lang">ES</a>
<a href="#" language='indonesian' class="lang">ID</a>
</div>
</div>
I was wondering if it was possible to store the chose language in the localStorage so that it stays the same after you refresh the page?
As already noted - use
localStorage. Gave you a working example, but it won't work on stackoverflow.com because ofallow-same-origin: