Reputation: 95
I would like to give the ability to a visitor to mark the containers of his choice in order to give him the ability to display only his/her favorite containers. What I cannot achieve is store their favorites in a cookie so they do not have to mark them from the beginning every time they visit my website (there are 36 containers in total). I have read the jquery cookie plugin documentation, also searched stack overflow and followed several tutorials and still have not any clue on how to use it. Thanks.
HTML
<div class="panel-player-favorite-option">
<div class="not-favorite"></div>
</div>
<div class="panel-player-favorite-option">
<div class="not-favorite"></div>
</div>
<div class="panel-player-favorite-option">
<div class="not-favorite"></div>
</div>
<div class="panel-player-favorite-option">
<div class="not-favorite"></div>
</div>
JQUERY
jQuery('.panel-player-favorite-option').click(function() {
jQuery(this).children().toggleClass("favorite not-favorite");
});
Upvotes: 3
Views: 684
Reputation: 133
First I assume that you have unique identifiers for each option element. I have added ids to each of the elements. I would also recommend that you use the option itself to have the favorite
class, thus removing the ambiguity of toggling that class on all of the selected option's children.
Here is my resulting HTML:
<div id="option-1" class="panel-player-favorite-option"></div>
<div id="option-2" class="panel-player-favorite-option"></div>
<div id="option-3" class="panel-player-favorite-option"></div>
<div id="option-4" class="panel-player-favorite-option"></div>
Then this code works for me, using jquery.cookie.js:
// set cookie name
var COOKIE_NAME = 'the_cookie';
// set cookie to automatically use JSON format
jQuery.cookie.json = true;
// retrieve or initialize favorites array
var favorites = jQuery.cookie(COOKIE_NAME) || [];
// collect all option elements in the dom
var options = jQuery('.panel-player-favorite-option');
// restore favorites in dom
for(var id in favorites)
{
options.filter('#'+favorites[id]).addClass("favorite");
}
options.click(function() {
// dom element
var element = jQuery(this);
// element id
var id = element.attr('id');
// toggle favorite class on the element itself
element.toggleClass("favorite");
// add or remove element id from array of favorites
if(element.hasClass("favorite"))
favorites.push(id);
else
favorites.splice(favorites.indexOf(id),1);
// store updated favorites in the cookie
jQuery.cookie(COOKIE_NAME, favorites);
});
Upvotes: 3