Reputation: 157
I'm trying to save the toggle state of collapsable boxes using cookies. Here's my code:
HTML:
<div class="box_container">
<div class="box_handle">
Title
</div>
<div class="box" data-title="admin_actions">
Content
</div>
</div>
Javascript:
$('div.box_container div.box_handle').click(function() {
$(this).next('.box').slideToggle('fast');
});
$.each($('div.box_container div.box_handle'), function(index,value){
if ($.cookie('show_box_' + $(value).next('.box').attr('data-title')) != 'closed'){
$(value).next('.box[data-title="' + $('.box').attr('data-title') + '"]').hide();
}
});
var new_value = "";
window.onbeforeunload = function() {
$.each($('div.box_container div.box_handle'),function(index,value){
new_value = ($(value).next('.box').css('display') == 'none') ? 'open' : 'closed';
$.cookie('show_box_' + $(value).next('.box').attr('data-title'), new_value);
});
}
Now, my problem is:
Any boxes other than the first one will always appear opened. It does set a cookie for it, but does not hide it if cookie is set to closed
Only for each first box on a page it works. How can I fix this?
Upvotes: 1
Views: 73
Reputation: 5466
Use onbeforeunload
function of javascript
window.onbeforeunload = function() {
//Declare cookie to close state
}
This function will be called every time page refreshes
Update:
To make loop through every value use this $.each
this way:
var new_value = "";
window.onbeforeunload = function() {
$.each($('div.box_container div.box_handle'),function(index,value){
new_value = ($(value).next('.box').css('display') == 'none') ? 'collapsed' : 'expanded';
$.cookie('show_box' + '_' + $(value).next('.box').attr('data-title'), new_value);
})
}
Update II :
Do this, it should work
window.onload = checkCon;
function checkCon(){
$.each($('div.box_container div.box_handle'),function(index,value){
if ($.cookie('show_box' + '_' + $(value).next('.box').attr('data-title')) != 'expanded'){
$(value).next('.box[data-title="' + $(value).next('.box').attr('data-title') + '"]').hide();
}
})
}
Upvotes: 1