Question

I am trying to save the state with a cookie using jquery but no luck. Can someone check what is wrong with my code?

$('.slide1').click(function() {
    $('.target1').slideToggle('slow', function() {
        $(this).toggleClass('.target1');
    });
    $.cookie('form_visible', $('.target1').css('display','block').toString());
    return false;
});         
$(function() {
    if($.cookie('form_visible') == 'true') {
        $('.target1').css('display','block');
    } else {
        $('.target1').css('display','none');
    }
});

http://jsfiddle.net/J9zQm/

Was it helpful?

Solution

Some problems:

  1. You need a plugin

    In order to use $.cookie, you need a plugin. You don't seem to know that.

  2. You are trying to store "[object Object]"

    $('.target1').css('display','block')
    

    returns an object (i.e. $('.target1'))

    Then,

    $('.target1').css('display','block').toString()
    

    returns

    "[object Object]"
    
  3. $('.target1') is empty

    You use

    $('.target1').slideToggle('slow', function() {
        $(this).toggleClass('.target1');
    });
    

    That is:

    • If $('.target1') is empty, you do nothing
    • If $('.target1') is not empty, you remove its class '.target1', so that following $('.target1') will be empty.

Here you have a working example of what you want, but using sessionStorage instead of $.cookie since I don't know how it works.

JS:

var $target1 = $('.target1');
$target1.toggleClass('hidden', sessionStorage.getItem('form_visible') != 'true');
$('.slide1').click(function() {
    $target1.slideToggle('slow', function() {
        $(this).toggleClass('hidden');
    });
    sessionStorage.setItem('form_visible', $target1.hasClass('hidden'));
});

CSS:

.target1.hidden{
    display:none;
}

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top