Question

I am trying to create a website that shows the selected language page at first visit. On click of the language name, the language name string (eg. French) gets stored in the web/local storage. And when the next time user visits the website, the language string is checked and specific language page is shown. I have written twelve functions for storing the language string on click of anchor tag of each language. Like this:

function english()
{
if(typeof(Storage)!=="undefined")
  {
  localStorage.clear();
  localStorage.language="English";
 window.location.reload();
  }
}

function french()
{
if(typeof(Storage)!=="undefined")
  {
  localStorage.clear();
  localStorage.language="French";
  window.location.href = "french.html";
  }
}

Is this method really efficient? I think creating multiple pages for multiple language is good for SEO rather than changing the text string on the fly. Till here when I check the Chrome developers console, the value of the string gets stored. But when I close the tab or the browser window the stored value is gone and the next time it cannot remember the language.

I am checking the language using this code (I have to do it for 12 languages):

window.onload = function() {
if (localStorage.language="Language")
  {
   window.location.href = "language.html";
  }
else if (localStorage.language="English")
  {
   window.location.href = "eng.html";
  }
else if (localStorage.language="French")
  {
  window.location.href = "french.html";
  }
else if (localStorage.language="Spanish")
  {
  window.location.href = "spanish.html";
  }

The code kinda stops after checking the first 'if' condition, true or false it just stops there and doesn't check the 'else if' condition beyond that.

Can someone please help me this?? The sample codes seems to store the value in web storage even after browser close but I cannot replicate it in mine.

Was it helpful?

Solution

The problem you had was using = instead of === to compare (as explained by wonko79). As to how to improve the code you did - there are quite a few issues here, most importantly a lot of repetition of the information of what to check for and what to apply which is a danger as it makes maintenance hard. I put together a solution for your problem using an object to store all the information about languages and creating the interface to pick the language from the same dataset:

var locales = {
    'us': {label: 'English',location:'english.html'},
    'de': {label: 'German',location: 'german.html'},
    'fr': {label: 'Français',location: 'french.html'},
    'nl': {label: 'Nederlands',location: 'dutch.html'}       
};

http://jsfiddle.net/codepo8/KzNUM/

I also wrote a longer blog post with more details http://christianheilmann.com/2014/01/08/this-developer-wanted-to-create-a-language-selector-and-asked-for-help-on-twitter-you-wont-believe-what-happened-next/

OTHER TIPS

As wonko79 already pointed out, the problem is that inside your if checks you actually reassign the variable instead of checking its content. To actually check the string contents for equality, you need to use two equals signs == (or three if you want to check for type equality too).

Furthermore, whenever you keep repeating yourself like that, it’s a good sign that you can improve a lot about your code. In this case, you always check if localStorage.language equals to a certain language, and if that’s the case, you then change the location to that language’s URL. So essentially, you are looking up the URL for the language stored in the local storage.

JavaScript has an efficient data structure for lookups: Objects. So, to improve your situation, we can first store the data in an object:

var languageUrls = {
    'language': 'language.html',
    'english': 'eng.html',
    'french': 'french.html',
    'spanish': 'spanish.html'
};

After we have done that, we can simply look up the values immediately based on the value of localStorage.language:

window.onload = function () {
    // we can perform the lookup by providing the *key* in brackets:
    var url = languageUrls[localStorage.language];

    // in case the key did not exist in our object, url will be null
    if (!url) {
        // so we might want to provide a fallback value here
        url = 'eng.html';
    }

    // now we have a valid URL in our `url` variable
    window.location.href = url;
}

And that’s all you need to do here; no need to repeatedly check with if statements, just a simple lookup. And when you want to add another language, you just need to add another entry to the languageUrls object.

A similar idea can be applied to your language-functions which change the language stored in the local storage. Instead of having multiple different functions, it’s enough to have a single function which takes the language as a parameter and then again uses the lookup to change the URL:

function changeLanguage (language) {
    // it’s always a good idea to normalize input;
    // in this case, keep everything lower-case
    language = language.toLowerCase();

    // this time, we might want to make sure first that the language is
    // valid – all valid languages are stored in our `languageUrls` object,
    // so we can use that
    var url = languageUrl[language];

    if (!url) {
        // There was no entry for the language—it’s not a valid language—so
        // we just return from the function here, not doing anything. We could
        // show an error though.
        return;
    }

    // so the language is valid, and the target URL is stored in `url`

    if (typeof(Storage) !== 'undefined') {
        // update the stored language; note that I’m not calling `clear`
        // because we might want to store other information in the future
        // too. It’s enough to just overwrite the stored language.
        localStorage.language = language;
    }

    // we still want to redirect, even if the storage was not available
    window.location.href = url;
}

And that’s already everything you need to set up. All that’s left is changing the calls from english() to changeLanguage('english') etc.

As far as i can see you do assignements instead of comparisons.

The following code should work:

    window.onload = function() {
    if (localStorage.language=="Language")
      {
       window.location.href = "language.html";
      }
    else if (localStorage.language=="English")
      {
       window.location.href = "eng.html";
      }
    else if (localStorage.language=="French")
      {
      window.location.href = "french.html";
      }
    else if (localStorage.language=="Spanish")
      {
      window.location.href = "spanish.html";
      }

See JavaScript Comparison and Logical Operators for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top