Home > Software design >  How to save a javascript function output with local storage/cookies? or any other way?
How to save a javascript function output with local storage/cookies? or any other way?

Time:11-10

I have a website that is loaded in english, and have manually translated each paragraph myself to french. With a simple function when you click on the translate_fr() onclick all the paragraphs are grabbed by their id's and switched to the french paragraphs stored in my .js files. When you click the translate_en() it reverts back to the english. Basically when the user clicks EN or FR I want that decision to carry over to every other page, I somehow need to store that function output and have it run automatically when they enter another page. If they enter the homepage for the first time and translate to French, everyother page should also be in french.

I left an example of one paragraph only, though if you need a better understanding here is the website on the domain lionkuts.ca

function translate_en(){
document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable products are used, any sensitivities or allergies will not be a problem.`;
}
   
function translate_fr(){
document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème.`;
} 
 <div class="wrapper3">
   <button class="translate" id="click1"            type="button"onclick="translate_en()">EN
   </button> 

   <button class="translate" id="click2" 
   type="button" onclick="translate_fr()">FR
   </button>
 </div>
 
    <p id="intro">
      Here at Lion Kuts we are a cat only
      establishment that offers a full range of services 
      from complete grooming, bathing to boarding. You and 
      your pet will be thrilled to know that only professional, 
      natural and biodegradeable products are used, any 
      sensitivities or allergies will not be a problem.
  </p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

enter image description here

All pages have the two functions set up like this, I just need the functions to run wether or not the decision was made to click either fr or en on the home page. If they clicked FR then that decision needs to be stored, and when the following page runs the translate_fr function runs automatically swapping all the paragraphs.

CodePudding user response:

I would not do it the same way but if you want to keep your structure you can do something like this:

function translate_fr() {
    localStorage.setItem('language', 'FR')
    document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème.`;
} 

function translate_en() {
    localStorage.setItem('language', 'EN')
    document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable products are used, any sensitivities or allergies will not be a problem.`;
}

const language = localStorage.getItem('language')
if(language === 'FR') {
    translate_fr()
}

CodePudding user response:

You're in luck, the API for this is very straight forward (and well described by MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).

Just store your value in the local storage with a key:

localStorage.setItem('your-key', 'your-value')

And afterwards get the value like this:

localStorage.getItem('your-key')

Beware of JSON encoding, though.


/e your example could be restructured like this, in its simples form:

function translate_en(){
localStorage.setItem('lang', 'en')
document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable products are used, any sensitivities or allergies will not be a problem.`;
}
   
function translate_fr(){
localStorage.setItem('lang', 'fr')
document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème.`;
}

// The moment this script executes, get the previous language selection, if any.
// Use it to repeat the users selection by automatically calling the right function
// depending on the language the user selected earlier.
const selectedLanguage = localStorage.getItem('lang')
if (selectedLanguage === 'en') {
    translate_en()
} else if (selectedLanguage === 'fr') {
    translate_fr()
}

CodePudding user response:

I more answer the part about the translation of the content, as you usually would do this by using a seperate content object. In this object you store all contents and with a js framework or vanilla js, you inject it in a specific paragraph. It is a more scalable approach as you can easily add de or any other language to the object as well, without changing the logic. A small example on how this would work:

const content = {
  en: {
    welcome: 'hi welcome on our website',
    body: 'a beautiful sentence'
  },
  fr: {
    welcome: 'bonjour, bienvenue sur notre site',
    body: 'une belle phrase'
  },
};


let currentLanguage = 'en' // or localStorage.getItem('locale')
const updateContent = (elem, msg) => elem.innerHTML = msg;
const handleLocalization = (locale) => {
  currentLanguage = locale;
  
  // and update localStorage
  // localStorage.setItem('locale', locale);
  updateContent(document.querySelector('#my-welcome-message'), content[currentLanguage].welcome);
    updateContent(document.querySelector('#my-body-message'), content[currentLanguage].body);
}

document.querySelector('#toggle-language').addEventListener('click', () => {
  handleLocalization(currentLanguage === 'en' ? 'fr' : 'en');
})

updateContent(document.querySelector('#my-welcome-message'), content[currentLanguage].welcome);

updateContent(document.querySelector('#my-body-message'), content[currentLanguage].body);
<p id="my-welcome-message"></p>
<p id="my-body-message"></p>

<button id="toggle-language">toggle language</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related