How to set a variable as Cookie (javascript)

I have translated a website and I want to remember which country a customer has selected. This is my code:

 $('.set_nl').click(function(){
   var translator = $('body').translate({lang: "nl", t: dict}); 
 });

 $('.set_de').click(function(){
   var translator = $('body').translate({lang: "de", t: dict}); 
 });

 $('.set_en').click(function(){ 
   var translator = $('body').translate({lang: "en", t: dict}); 
 });

How can I achieve this with cookies?

Upvotes: 0

Views: 1214

Answers (2)

Francesco Gusmeroli
Francesco Gusmeroli

Reputation: 661

To store a cookie you have to set a name and save it into a certain pattern:

document.cookie = "username=John Doe";

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337580

Firstly to set a cookie using Javascript you can use the code outlined in this question, or as you have already included jQuery in the page you can use the $.cookie library.

From there you can set the value when a choice is made, then retrieve the value on load of the page to set the language the user previously set.

Also note that you can DRY up the multiple click handlers on the button which set the language by using a data attribute. Try this:

$('.lang').click(function() {
  var lang = $(this).data('lang');
  var translator = $('body').translate({
    lang: lang,
    t: dict
  });
  $.cookie('lang', lang);
});

// on load
$('body').translate({
  lang: $.cookie('lang'),
  t: dict
});
<a href="#" class="lang" data-lang="nl">NL</a>
<a href="#" class="lang" data-lang="de">DE</a>
<a href="#" class="lang" data-lang="en">EN</a>

Upvotes: 1

Related Questions