coolio83000 coolio83000 - 2 months ago 20
HTML Question

Use localStorage.setItem to keep same show/hide divs

I work with a function in my main page. All works fine, I just want to know how to keep the select language in a page when i click on a link and go in another page.

For example id="en" is the language by default, but if I want to use id="fr" in my main page, and click on link who will send me in another page. I will come back to id="en". So to keep the same language how can I use this function :

localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");


Here is the jsfiddle of the function that I use to switch language:

https://jsfiddle.net/kodjoe/chvw181j/



$(document).ready(function() {
$('.lan').hide();
$('.en').show();
});

$('.button').click(function(event) {
$('.lan').hide();
var selectedLanguage = $(this).attr('id');
var setActiveLanguage = "." + selectedLanguage;
$(setActiveLanguage).show();

localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
});

.button {
cursor: pointer;
padding: 0px 30px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="button" id="en">EN</a>
<a class="button" id="fr">FR</a>
<a class="button" id="de">DE</a>


<div class="lan en">1</div>
<div class="lan fr">2</div>
<div class="lan de">3</div>
<div class="lan en">4</div>
<div class="lan fr">5</div>
<div class="lan de">6</div>




Answer

firstly store your value

$('.button').click(function(event) {
  $('.lan').hide();
  var selectedLanguage = $(this).attr('id');
  var setActiveLanguage = "." + selectedLanguage;
  $(setActiveLanguage).show();

localStorage.setItem("language", selectedLanguage); //storing under the key of language

});

then fetch the value on ready in your .ready function

var langStored = localStorage.getItem("language");

if no values is stored it will return null.

So put conditions there what you want to do when you get langStored and when you get null

take a peek at: codepen

Comments