简体   繁体   中英

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> 

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

Set / Get the localStorage item.

localStorage.setItem('selectedLang', $(this).attr('id'));

localStorage.getItem('selectedLang');

Documentation : HTML5 Web Storage

Code for your example

$(document).ready(function() {
    $('.lan').hide();
    var classSel = localStorage.getItem('selectedLang') ? localStorage.getItem('selectedLang') :  'en';
    //Get the value from localStorage and show that class only
    $('.'+classSel).show();

    $('.button').click(function(event) {
        $('.lan').hide();
        $("." + $(this).attr('id')).show();
        //Set the localStorage value
        localStorage.setItem('selectedLang', $(this).attr('id'));
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM