Skip to content

Instantly share code, notes, and snippets.

@MathRivest
Last active August 29, 2015 13:57
Show Gist options
  • Save MathRivest/f46e7e1156f2636dd773 to your computer and use it in GitHub Desktop.
Save MathRivest/f46e7e1156f2636dd773 to your computer and use it in GitHub Desktop.
Remember cookies state
<ul class="m-items">
<li>
<input type="checkbox"/>
</li>
<li>
<input type="checkbox"/>
</li>
<li>
<input type="checkbox"/>
</li>
</ul>
var $items = $('.m-items li');
$items.each(function(i, $el){
var newId = 'item-'+ i,
theCookie = $.cookie('checkbox_' + newId);
$el.id = newId;
if(theCookie){
// Check the checkbox and mark the item
$(this).find('input[type="checkbox"]').attr('checked', 'checked');
}
});
// When user mark an item
$items.find('input[type="checkbox"]').on('click', function(){
var $item = $(this).parents('li'),
itemID = $item.attr('id'),
cookieName = 'checkbox_' + itemID;
if($.cookie(cookieName)){
// Delete the cookie
$.removeCookie(cookieName);
}else{
// Write the cookie
$.cookie(cookieName, itemID, { expires: 365 });
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment