简体   繁体   中英

Create multilingual website with JavaScript

I'm new to coding, and I'm trying to create a multilingual website. So I've found the following implementation to be working:

JS

let langs = document.querySelector(".langs"),
     link = document.querySelectorAll("a"),
     lgmenu = document.querySelector(".lgmenu");
     lglanguage = document.querySelector(".lglanguage");

link.forEach(el=>{
     el.addEventListener("click", ()=>{
          langs.querySelector(".active").classList.remove("active");
          el.classList.add("active");

          let attr = el.getAttribute("language")

          lgmenu.textContent = data[attr].lgmenu
          lglanguage.textContent = data[attr].lglanguage

     })

})

let data = {
     romanian: {
          lgmenu: "Meniu",
          lglanguage: "Alege limba"
     },
     english: {
          lgmenu: "Menu",
          lglanguage: "Choose language"
     }
}


window.localStorage.setItem("langs", "romanian");
window.localStorage.setItem("langs", "english");
window.localStorage.getItem('langs');

My questions:

  1. How to save the user's language selection? So the language won't reset on refresh or navigating between pages. I've read that I have to do it with localStorage. But I have no idea how to do this.

  2. How to show the currently selected language in the header bar? https://imgur.com/a/8IGC07k

If you can please advise. Many thanks

Best regards, Veaceslav

  1. To set any value to localStorage, simply do:

     localStorage.setItem('key', value);

    To retrieve the value, do:

     window.localStorage.getItem('key');
  2. Add a script to retrieve the value and set an element's innerHTML equal to that value.

More details on local storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM