Skip to content

Instantly share code, notes, and snippets.

@ariakm25
Created February 16, 2019 10:40
Show Gist options
  • Save ariakm25/9d531c79acd7777b62eeccb787d9296a to your computer and use it in GitHub Desktop.
Save ariakm25/9d531c79acd7777b62eeccb787d9296a to your computer and use it in GitHub Desktop.
JQuery JS Cookie
/**
* Cookies WATCHLIST
* js.cookie.js
**/
// cek cookies favorites
if (typeof Cookies.get('favorites') === 'undefined') {
Cookies.set('favorites',[])
}
var favorites = JSON.parse(Cookies.get('favorites')) || [];
// menambahkan kelas pada item yang saved
favorites.forEach(function(favorite) {
$('#'+favorite).closest('.postgayn').addClass('saved');
$('#'+favorite).closest('.simpen').text('Remove');
});
// Menambah/Menghapus
$(document).on('click','.simpen', function(e) {
var id = e.target.id,
item = $(this).closest('.postgayn'),
index = favorites.indexOf(id);
// return jika tidak memiliki ID
if (!id) return;
// item tidak saved (menambahkan item ke cookies)
if (index == -1) {
favorites.push(id);
item.addClass('saved');
$(this).text('Remove');
// item sudah saved (menghapus item dari cookies)
} else {
favorites.splice(index, 1);
item.removeClass('saved');
$(this).text('Bookmark');
}
// simpan array ke cookies
Cookies.set('favorites', JSON.stringify(favorites));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment