Reputation: 171
I would really appreciate some help implementing a cookie to save the state of a toggle in JQuery, I have created the toggle using he code in the fiddle below and have tried implementing the answer from BARMAR in the thread below but this changes the state of the tags just below it and closes the tags every time the page is loaded when I try to implement it.
Thread I have looked at: Preserve toggle state using jQuery
My Fiddle thus far:
<script type="text/javascript">
$(function() {
$('#slide1').click(function() {
$('.slide1').slideToggle('slow');
$('.toggle1').toggle();
return false;
});
});
</script>
<a href="#" id="slide1">Slide Toggle
<span class="toggle1">+</span>
<span class="toggle1" style="display:none;">-</span>
</a>
<div class="slide1" style="display:none; background-color:#4CF;width:100px;height:200px;"></div>
Any help would be appreciated,
Thanks!
Upvotes: 1
Views: 2953
Reputation: 14619
Cozmoz,
You can use the "cookie" plugin referenced here: http://plugins.jquery.com/cookie/ To implement it in your solution, add the javascript file of the plugin in your sources and don't forget to reference it from your page using it.
Then, a few javascript:
$(document).ready(function() {
// check the cookie when the page loads, opens it if needed (hidden by default)
alert($.cookie('currentToggle'));
if ($.cookie('currentToggle') === 'visible') {
togglePanel(true);
}
//handle the clicking of the show/hide toggle button
$('#slide1').click(function() {
//toggle the panel as required, base on current state
if ($('#slide1').text() === "Slide Toggle +") {
togglePanel(true);
}
else {
togglePanel(false);
}
});
});
function togglePanel(show) {
var panel = $('.slide1panel');
var button = $('#slide1');
if (show) {
panel.slideToggle('slow');
button.text('Slide Toggle -');
$.cookie('currentToggle', 'visible', { path: '/' });
} else {
panel.slideToggle('slow');
button.text('Slide Toggle +');
$.cookie('currentToggle', 'hidden', { path: '/' });
}
}
With your html simplified to:
<a href="#" id="slide1">Slide Toggle +</a>
<div class="slide1panel" style="display:none; background-color:#4CF;width:100px;height:200px;"></div>
Update of your fiddle: http://jsfiddle.net/fE6DJ/5/
It's working ;-)
Upvotes: 1