Search code examples
javascriptjquerylocal-storagemodernizr

addClass - LocalStorage Problems


I'm working on a site and want to store a class in localStorage although I'm having some problems.

Here's the HTML:

<ul class="type">
  <li id="1" class="current">Example 1</li>
  <li id="2">Example 2</li>
</ul>

I have some jQuery that adds a class to one of the examples when clicked.

When the class current is active, it changes some values on the site. Basically, when you visit the site, #1 already has the class current but if I add the class the #2, I want localStorage to remember which element had the class current.

Here's what I've wrote so far of localStorage but I don't think it's right. (P.S. I'm using Modernizr).

function temp_type(){
  var type = $('.type li').hasClass('current');
}

$('#1').click(function() {
  $('#2').removeClass('current');
  $(this).addClass('current');
  if(Modernizr.localstorage) localStorage.setItem('temp_type'), $('.type li').hasClass('current');
});

$('#2').click(function() {
  $('#1').removeClass('current');
  $(this).addClass('current');
  if(Modernizr.localstorage) localStorage.setItem('temp_type'), $('.type li').hasClass('current');
});

if(Modernizr.localstorage){
  var type = localStorage.getItem('temp_type');
  if(type){
    $('.type li').hasClass('current');
    temp_type();
  }
}

Also, is there a way to test if localStorage is working or not?


Solution

  • This can be written in a simple way, try the below one

    HTML

    <ul class="type">
      <li id="1">Example 1</li>
      <li id="2">Example 2</li>
    </ul>
    <br />
    <a href="javascript:void(0);">Check Storage</a>
    

    Script

    $(document).ready(function(){
        $('.type li').on('click', function(event){
            $('.type li').removeClass('current');
            $(this).addClass('current');
            if(Modernizr.localstorage){
                window.localStorage['temp_type'] = $(this).attr('id'); /*Storing the id of the selected element*/
            }
        });
    
        $('a').on('click', function(event){ 
            alert(window.localStorage['temp_type']); /*Check the current storage*/
        });
    });
    

    CSS

    li.current {
        color: red;
    }
    

    Demo JS http://jsfiddle.net/5vmBe/3/

    Hope this will help you.