3

My home page has a couple of links: one for English version and the other for French version. Something like this:

<a class="ensite" href="/en">English</a>
<a class="ensite" href="/fr">French</a>

I want to use JavaScript to remember the last choice made by visitors and when they come again, they don't have to choose the language one more time because I want them to be autoredirected to the preferred language using cookies.

P.S. the visitors are strangers, not registered users. I want to store cookies in visitors' browsers, not in the database. Please, help me by providing me with the full solution.

curveball
  • 4,320
  • 15
  • 39
  • 49
Jefathey
  • 33
  • 5
  • Use cookies/local storage – Znaneswar Sep 02 '17 at 08:39
  • you can pass lang parameter in requested url or else you can create cookie for that – CHiRAG Sep 02 '17 at 08:40
  • it its registered user then you can take language preference from registration time as well – CHiRAG Sep 02 '17 at 08:41
  • What does the link do? Redirect to new page page or triggers a javascript command that shows the words in the language chosen? In your case, I think you want to remember the language setting chosen by the user, so all words will be displayed in that language. Cookies is the simplest and right solution I think. – Aesthetic Sep 02 '17 at 08:51
  • Possible duplicate of [How do I create and read a value from cookie?](https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie) – Darren H Sep 02 '17 at 09:11

2 Answers2

1

Gelerally, the idea is: set handlers on links and upon clicking save preferred version into localStorage. Then every time user loads any page of your site, just check, whether the url contains the language context ("en"/"fr") the user chose before. If yes - do nothing, user opened the right version; if not - redirect him to the previously saved version. The following is a Vanilla approach (not properly tested). You will have to tweak it (attachEvent etc.) or use jQuery library to implement similar ideas in a shorter and more cross-browser way.

<a class="ensite" href="/en">English</a>
<a class="ensite" href="/fr">French</a>

JS:

function LanguageManager(selector) {
    this.langLinks = document.querySelectorAll(selector);
}
LanguageManager.prototype.setHandler = function() {
    var self = this;
    this.langLinks.forEach(function(langLink) {
        langLink.addEventListener("click", self.handler, false);
    });   
}
LanguageManager.prototype.redirect = function() {
    var link = storageManager.restoreDataFromStorage();
    if(link && !~window.location.href.indexOf(link)) window.location.href = link;
}
LanguageManager.prototype.handler = function() { 
    var e = event || window. event;
    var elem = e.target || e.srcElement;
    if(e.preventDefault) e.preventDefault(); else e.returnValue = false;
    storageManager.saveDataToStorage(elem.href);
    location.href = elem.href;
}
function StorageManager() {
    this.storageName = "languageVersion";
    this.storageData = null;
}
StorageManager.prototype.isStorageAvailable = function(type) {
  try {
    var storage = window[type], x = '__storage_test__';
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch(e) { return false; }
}
StorageManager.prototype.saveDataToStorage = function(data) {
    if(!this.isStorageAvailable('localStorage')) { 
        this.storageData = data; 
          return false;
  }
    try {
        localStorage.setItem(this.storageName, JSON.stringify(data));
        return this.storageName; 
    } catch(e) { 
        this.storageData = data; 
        return false;
    }
}
StorageManager.prototype.restoreDataFromStorage = function() {
    if(this.storageData) return this.storageData;
    return JSON.parse(localStorage.getItem(this.storageName));
}
var storageManager = new StorageManager();  
var languageManager = new LanguageManager(".ensite");  
languageManager.setHandler();
languageManager.redirect();

Also notice, that there may be issues depending on how you implement language contexts on your site. You can start with my code on your own and tweak it or find someone else to get this properly done.

curveball
  • 4,320
  • 15
  • 39
  • 49
  • good! But pay attention to cross-browserness and your links should actually contain "http ://site.com/en" – curveball Sep 02 '17 at 13:18
  • afrer using the code i face aproblem when i try to go to home page from another browser it not working and it not working in firefox some one told me to use this library https://github.com/js-cookie/js-cookie – Jefathey Sep 02 '17 at 14:47
  • cookies, storages, etc. are bound to the current browser. If you open the page in a new browser - it knows nothing about your previous actions, stored information etc. in another browser. The users have to repeat the steps in the new browser. That library just provides an interface for the native cookies implementation which is an alternative for storages. – curveball Sep 02 '17 at 15:04
  • besides, some browsers can have so called "private" mode. If activated by user, then passwords, cookies and other stuff that comes from the page are not getting stored which makes the whole approach not working. – curveball Sep 02 '17 at 15:20
  • check these answers which suppose another (server-side) approach - headers: https://stackoverflow.com/questions/17803702/auto-detect-language-and-redirect-user https://stackoverflow.com/questions/36985812/redirect-users-based-on-browser-language-not-in-php – curveball Sep 02 '17 at 15:22
  • also check some different JS appoach based on navigator.language property where you don't have to store anything but it is still unreliable: https://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference – curveball Sep 02 '17 at 15:26
1

Just tested this, it works perfect.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<a class="ensite" href="" onclick ="localStorage.setItem('language','en')">English</a>
<a class="ensite" href="" onclick = "localStorage.setItem('language','fr')">French</a>

<script>

$(document).ready(function(){

var language =  (localStorage.getItem('language') == null)? 'en' : localStorage.getItem('language');

console.log(language);
})

</script>
M. Waheed
  • 877
  • 1
  • 8
  • 8