Hi All
I'm working on a toggle view script, which flips between 2 views (grid & list). I have it all working fine so far, but I'm trying to use a cookie to remember the users selection on page refreshes (using a jQuery cookie plugin). However, if the view is in the altered state, it takes 2 clicks to get it to change the next time.
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("span.switch_thumb").toggle(function(){
$j("span.switch_thumb").addClass("swap");
$j("ul.display").fadeOut("fast", function() {
$j(this).fadeIn("fast").addClass("thumb_view");
$j.cookie('viewState', 'thumbs');
});
}, function () {
$j("span.switch_thumb").removeClass("swap");
$j("ul.display").fadeOut("fast", function() {
$j(this).fadeIn("fast").removeClass("thumb_view");
$j.cookie('viewState', 'list');
});
});
// COOKIES
// view state
var viewState = $j.cookie('viewState');
// Set the user's selection for the viewState
if (viewState == 'thumbs') {
$j("ul.display").addClass("thumb_view");
$j("span.switch_thumb").addClass("swap");
};
});
I know why this is, as the script is only running one way, adding a class to change the view. But how can I re-write the script so that it runs both ways, as in, if the class is already added when the page is loaded (because of the cookie) it will work the opposite way and remove the class?
- EDIT * * *
Ok, thanks to zincorp, I've now greatly simplified the script - but the problem is now, how do I add my cookie states, as in my previous script?
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("span.switch_thumb").click(function () {
$j("span.switch_thumb").toggleClass("swap");
$j("ul.display").fadeOut("fast", function() {
$j(this).fadeIn("fast").toggleClass("thumb_view");
});
});
// COOKIES
// view state
var viewState = $j.cookie('viewState');
// Set the user's selection for the viewState
if (viewState == 'thumbs') {
$j("ul.display").addClass("thumb_view");
$j("span.switch_thumb").addClass("swap");
};
});