6

I have a div that expands/collapses to an automatic height based on button clicks. I have that working just fine, but I would like to use jquery.cookie.js to remember if the user expanded it or not, so that it stays open on page refresh. I've looked at similar questions

e.g. Keep toggle state on divs using cookie.js after page refresh

however I can't seem to get this to work for my situation. It's not just a straight show/hide, and I'm having trouble figuring out the syntax to properly set and use the cookie. Here is a fiddle of my working code, perhaps someone can help me?

http://jsfiddle.net/j2Rsy/

and here is the relevant code:

$('#viewless').hide();
$('#viewmore').click(function(){
    var el = $('#resize01'),
    curHeight = el.height(),
    autoHeight = el.css('height', 'auto').height();
    el.height(curHeight).animate({height: autoHeight}, 500);
    $('#viewmore').toggle();
    $('#viewless').toggle();
});

$('#viewless').click(function(){
$('#resize01').animate({height: '190'}, 500);
    $('#viewmore').toggle();
    $('#viewless').toggle();
});
Community
  • 1
  • 1
Patrick
  • 872
  • 1
  • 5
  • 14

1 Answers1

8

Try

$('#viewless').hide();
$('#viewmore').click(function(){
    var el = $('#resize01'),
        curHeight = el.height(),
        autoHeight = el.css('height', 'auto').height();
    el.height(curHeight).animate({height: autoHeight}, 500);
    $('#viewmore').hide();
    $('#viewless').show();

    $.cookie('viewmore', true);

});

$('#viewless').click(function(){
    $('#resize01').animate({height: '190'}, 500);
    $('#viewmore').show();
    $('#viewless').hide();

    $.cookie('viewmore', false);
});

if($.cookie('viewmore') == 'true'){
    $('#viewmore').click();
} else {
    $('#viewless').click();
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    This works! So, if I understand correctly, you are just initiating the click functions that are already established? – Patrick May 10 '13 at 01:01
  • Thank you very much, jQuery (and javascript in general) is still very new to me. I appreciate it. – Patrick May 10 '13 at 01:16
  • hey there @Arun P Johny do you have any idea how can I apply something similar in my situation please? thanks http://stackoverflow.com/q/32687806/4642215 – typo_ Sep 25 '15 at 08:21