skip to Main Content

I need to replace texts on multiple pages by clicking a simple button. What is the leanest switch between two languages?

This only changes text in the first div. I need to have language change applied across the site.

var text1 = document.getElementById('english');
var text2 = document.getElementById('swedish');

const swap = () => {
  if (text1.classList.contains("hidden")) { //if english contains class 'hidden'
    text1.classList.remove("hidden"); //remove hidden class from english
    text2.classList.add("hidden"); //add hidden class to swedish
  } else {
    text1.classList.add("hidden"); //add hidden class to english
    text2.classList.remove("hidden"); //remove hidden class from swedish
  }
}
.hidden {
  display: none;
}
<button onclick="swap()">Switch Text</button>

<div class="content">
  <div id="english">
    <h1>Welcome</h1>
    <p>English text</p>
  </div>
  <div id="swedish" class="hidden">
    <h1>Vällkommen</h1>
    <p>Svensk tekst</p>
  </div>
</div>

2

Answers


    1. Use lang as you are supposed to
    2. Use classList.toggle

    This script can be included on each page that has the lang set to either languages.

    Change the lang to whatever you need. lang="en"/lang="sv" and change the script accordingly

    Remove the comments // from the lines with localStorage and remove this line on your site: let savedLang = "se_SV";

    window.addEventListener("DOMContentLoaded", () => {
      //let savedLang = localStorage.getItem("lang") || "gb_EN";
      let savedLang = "se_SV";
      const btn = document.getElementById("swap");
      btn.dataset.lang = savedLang;
    
      btn.addEventListener("click", (e) => {
        const tgt = e.target;
        let lang = tgt.dataset.lang;
        lang = lang === "gb_EN" ? "se_SV" : "gb_EN";
        tgt.dataset.lang = lang;
        // localStorage.setItem("lang",lang);
        const divs = document.querySelectorAll('div[lang]');
        divs.forEach(div => div.classList.toggle('hidden', div.lang === lang));
      })
      btn.click()
    })
    .hidden {
      display: none;
    }
    <button type="button" id="swap" data-lang="gb_EN">Switch Text</button>
    
    <div class="content">
      <div lang="gb_EN">
        <h1>Welcome</h1>
        <p>English text</p>
      </div>
      <div lang="se_SV" class="hidden">
        <h1>Vällkommen</h1>
        <p>Svensk tekst</p>
      </div>
      <div lang="gb_EN">
        <h1>Welcome</h1>
        <p>English text</p>
      </div>
      <div lang="se_SV" class="hidden">
        <h1>Vällkommen</h1>
        <p>Svensk tekst</p>
      </div>
    </div>
    Login or Signup to reply.
  1. Here is a simple (‘lean’) way to load/show languages. If you need the language to persist, you need to store the selected language. Most convenient is to do that in localStorage. That is not supported here, so I created the same snippet in Stackblitz with localStorage to save the selected language.

    The snippet uses event delegation, data attributes an an .active css class to activate/display the right language divs.

    document.addEventListener(`click`, handle);
    document.querySelector(`[data-lang="de-DE"]`).click();
    
    function handle(evt) {
      if (evt.target.dataset?.lang) {
      const nwLang = evt.target.dataset.lang;
      return document.querySelectorAll(`[lang]`)
        .forEach(el => 
          el.classList[el.lang === nwLang ? `add` : `remove`](`active`));
      }
    }
    *:not(html)[lang] {
      display: none;
    }
    
    *:not(html)[lang].active {
      display: initial;
    }
    <button type="button" data-lang="en-GB">EN</button>
    <button type="button" data-lang="se-SV">SV</button>
    <button type="button" data-lang="de-DE">DE</button>
    <button type="button" data-lang="fr-FR">FR</button>
    
    <div class="content">
      <div lang="en-GB">
        <h1>Welcome</h1>
        <p>English text</p>
      </div>
      <div lang="se-SV">
        <h1>Vällkommen</h1>
        <p>Svensk tekst</p>
      </div>
      <div lang="de-DE">
        <h1>WillKommen</h1>
        <p>Deutscher Text</p>
      </div>
      <div lang="fr-FR">
        <h1>Bienvenue</h1>
        <p>Texte Française</p>
      </div>
    </div>

    Or use this factory to switch between two languages.

    function languageToggleFactory({ switchBtn, first, second }) {
      const store = {
        get current() { return localStorage.getItem(`language`); },
        set current(value) { localStorage.setItem(`language`, value); },
        get langItems() { return document.querySelectorAll(`[lang]`); },
      };
      const toggleLang = lang => {
        store.current = lang ?? (store.current === first ? second : first);
        switchBtn.lang = store.current;
        return store.langItems
          .forEach(el => el.classList.toggle(`active`, el.lang === store.current) );
      };
      const loadPage = () => {
        store.current = store.current ?? first;
        return toggleLang(store.current);
      };
    
      return { loadPage, toggleLang, };
    }
    // usage
    const switchBtn = document.querySelector([yourBttn]);
    const { loadPage, toggleLang } = languageToggleFactory({
      switchBtn, 
      first: `sv-SE`, 
      second: `en-GB` });
    loadPage();
    switchBtn.addEventListener(`click`, toggleLang);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search