Can someone tell me why this doesn't work:
$(docu开发者_开发问答ment).ready(function() {
$("#cookie").text("expanded");
//panel toggle
$(".btn-slide").click(function() {
$("#panel").slideToggle("slow");
//set the name and value of the cookie
$.cookie('panel', 'collapsed');
$("#cookie").text("collapsed");
}, function() {
$("#panel").slideDown("slow");
//set the name and value of the cookie
$.cookie('panel', 'expanded');
$("#cookie").text("expanded");
});
// cookie
var panel = $.cookie('panel');
// Set the user's selection for the state
if (panel == 'collapsed') {
$("#panel").hide();
};
});
jsFiddle Example
I don't see anyting wrong, but on refresh the panel doesn't keep it's state (whether open or closed). It just returns to the closed default state. I'm using a plugin for the cookies.
The plugin behavior works as expected. The problem is that you've misunderstood how the click() event works.
You've given it two function arguments assuming that they will be called in alternatively to set the cookie values. Since only the second method is ever called, your state will always be expanded
.
Also, you've set display: none;
on the panel with your CSS, which means it won't expand even if the proper state was set. Because in your JS, you only check whether it's collapsed and hide it.
It works as expected once you fix these issues. Here's the updated code.
$(document).ready(function() {
$("#cookie").text("expanded");
$(".btn-slide").click(function() {
$("#panel").slideToggle("slow");
var state = ($.cookie('panel') != 'collapsed') ? 'collapsed' : 'expanded';
$.cookie('panel', state);
$("#cookie").text("collapsed");
});
var panel = $.cookie('panel');
if (!panel) {
$.cookie('panel', 'expanded');
}
if (panel == 'collapsed') {
$("#panel").hide();
} else {
$("#panel").slideDown();
};
});
And here's the fiddle : http://jsfiddle.net/RJMhT/157/
Keep in mind that I haven't set a default, so for the initial loads it will be expanded. And once you've actually changed the state it will remember it.
HI!
Well to me the question was pretty clear!
Working Ex:
$(document).ready(function() {
// default:
$("#panel").hide();
$('#cookie').text('collapsed');
// if cookie exist:
if ($.cookie('panel') == 'open') {
$('#panel').show();
$('.slide').addClass('expanded');
$('#cookie').text('expanded');
}
$(".slide").click(function() {
$(this).toggleClass('expanded'); // toggle class
if ($(this).hasClass('expanded')) { // now we check what happend:
$.cookie('panel', 'open', {expires: 1} ); //create cookie if .expanded is added to button
$('#cookie').text('expanded');
}
else {
$.cookie('panel', null, {expires: 1} ); // else: delete cookie
$('#cookie').text('collapsed');
};
$(this).prev('#panel').slideToggle(800);
});
});
And here is a JSFiddle DEMO
精彩评论