Issue
I have a bit of the problem trying to implement language switcher/preference
I made a localstorage item for that, but got a problem because of reload need.
function lang_displayed_settings() {
if (localStorage.getItem("language") === "pl") {
window.location.hash = "#pl"
location.reload();
}
}
I tried to do a function on window load to get a item with preferred language but I can't really make it to be reload automatically. Or I'm getting a loop when window is just reloading on load.
I need a function which works on href
s etc.
Now I have no idea what I can change to get it working! Hope someone made it better than me.
(code from above is a clear one, before me uselessly trying)
Solution
If the language
item in the localstorage is already set to "pl"
, your code will reload and will find the property set to the same value again and will just keep reloading your page.
The solution is to add another if condition to check for the existence of #pl
in window.location.hash
so you wouldn't have to reload the page when the hash is already set:
function lang_displayed_settings() {
if (localStorage.getItem("language") === "pl") {
if (window.location.hash === "#pl") {
return;
} else {
window.location.hash = "#pl";
return location.reload();
}
}
}
If you want the language setting to support many languages, you can load it from the localsorage on the first loading of the page and then run the hashing logic as follows:
window.onload(() => {
const lang = localStorage.getItem("language")
if (window.location.hash === `#${lang}`) {
return;
} else {
window.location.hash = `#${lang}`;
return location.reload();
}
})
Answered By - Yahya Eddhissa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.