How to change the language of a website by Javascript?

Asked

Viewed 233 times

-3

Save guys, I’m trying to change language a site but by Javascript I can not at all.

The way I’ve been trying is as follows. But when I try to re-load the page, the link does not change, does not go out of place. Does anyone know how to fix it or has a better way to do it??

Thank you.

       <a  href="#eng" data-reload>ENGLISH</a>
       <a  href="#ita" data-reload>ITALIANO</a>
    
       
  
       <p id="hi">

           Welcome everyone!

        </p>



  <script>
      //define language reload anchors//
      var dataReload = document.querySelectorAll("[data-reload]");


      //language translations//

      var language = {
          eng: {
              welcome: "Welcome everyone!"
          },

          ita: {
              welcome: "Benvenuti a tutti!"
          }

      };

      //define language via window hash//

      if (window.location.hash) {
          if (window.location.hash === "#ita") {
              hi.textContent = language.ita.welcome;
          }

    }
      
    //define language reload onclick illiteration

    for (i = 0; i <= dataReload.length; i++) {

        dataReload[i].onclick = function() {
           location.reload(true); 
        };
    }
    
  </script>

1 answer

1

You don’t need to reload the page, you can simply assign a value to window.location.hash at the click of the buttons and put the functionality inside another Function.

var dataReload = document.querySelectorAll("a[data-reload]");
var hi = document.getElementById("hi");
var language = {
  eng: {
    welcome: "Welcome everyone!"
  },

  ita: {
    welcome: "Benvenuti a tutti!"
  }

};

var setLanguage = () => {

  if (window.location.hash === "#ita") {
    hi.textContent = language.ita.welcome;
  } else {
    hi.textContent = language.eng.welcome;
  }

}

for (i = 0; i < dataReload.length; i++) {
  dataReload[i].onclick = function(e) {
    window.location.hash = this.getAttribute("href");
    setLanguage();
  }
}

setLanguage();
<a href="#eng" data-reload>ENGLISH</a>
<a href="#ita" data-reload>ITALIANO</a>
<p id="hi">
  Welcome everyone!
</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.