skip to Main Content

I have a HTML template with a script to manage cookies permissions:

<!DOCTYPE html>
  <html lang="fr">
    <head>
      <script id="consentementCookiesScript"></script>

The cookies permissions’ language is set according with the Lang att into the tag html.
I manage creating a btn to change dynamically the Lang att:

<div id="toolbar" class="toolbar">
  <div id="changeLangElement" style="color: white">Français</div>
</div>

through this function:

changeLangElement.onclick = function () {
  currentLang = currentLang === "fr" ? "en" : "fr";
  translatePage(currentLang);
  document.documentElement.lang = currentLang;
};

Is there any way to execute the script again with the right language after click the button?

2

Answers


  1. I think you have to add an Event listener attached to that button or div like this :

    const changeLangElement = document.querySelector('#changeLangElement') ; 
    
    changeLangElement.addEventListener('click' , () => {
      currentLang = currentLang === "fr" ? "en" : "fr";
      translatePage(currentLang);
      document.documentElement.lang = currentLang;
    }) ;
    
    Login or Signup to reply.
  2. You can either move the currentLang variable outside of the function scope or use closure like so:

    
    function createLangToggleHandler() {
      let currentLang = "en";
    
      return function () {
        currentLang = currentLang === "fr" ? "en" : "fr";
        translatePage(currentLang);
        document.documentElement.lang = currentLang;
      };
    }
    
    const changeLangElement = document.getElementById("changeLang");
    changeLangElement.onclick = createLangToggleHandler();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search