Reputation: 7449
I am using the jQuery Accordion, and have two Accordions on a single page. I want to store the selected index of each Accordion in a cookie. To do this, I have the following code (with the jquery.cookie.js library referenced).
function accordionsInitAll() {
$(document).ready(function () {
accordionInit("#accordion1");
accordionInit("#accordion2");
});
}
function accordionInit(sAccordion) {
var accordion = $(sAccordion);
var index = $.cookie(sAccordion);
var active;
if (index !== null) {
active = accordion.find("h3:eq(" + index + ")");
} else {
active = 0;
}
$(sAccordion).accordion(
{
active: active,
change: function (event, ui) {
var index = $(this).find("h3").index(ui.newHeader[0]);
$.cookie(sAccordion, index);
}
});
}
Each Accordion section contains links that reference the same page as the jQuery is on (with different parameters). The functions work in that some state is getting saved. The problem is, the behavior seems random. Sometimes it works perfectly, sometimes the active element cookie is null when it should have a value, and sometimes the selected index is switched between the two Accordions.
I am stumped, and the only thing that I can think of is that it's a closure issue, with some variable not being captured correctly.
Is this a closure issue, or do I have some other bug that is causing the problem?
Thanks, Erick
Edit 11/510 with solution
The problem turned out to be that for some reason, the cookie library that I was using would sometimes set the same cookie more than once, leading to a situation where there were two cookie values with the exact same key. The cookie right order was not the same as read order, leading to bizarre behavior.
Once I switched the cookie library to http://code.google.com/p/cookies/ I no longer had any problems. Thanks to everyone who helped!
Upvotes: 2
Views: 400
Reputation: 31173
UPDATED
$(function() {
var accordions = ['dataAccordion', 'regionAccordion'];
var index,cookie;
$.each(accordions,function(i, item) {
cookie = $.cookie(item);
index = (null !== cookie) ? parseInt(cookie) : 0;
$acdn = $('#' + item);
$acdn.accordion({
autoHeight: false,
fillSpace: false,
clearStyle: true,
active: index,
change: function(event, ui) {
index = $(this).find("h3").index(ui.newHeader[0]);
$.cookie(this.id, index, {
expires: 10
});
}
});
});
});
- NOTE: the use of
parseInt()
Upvotes: 1