Reputation: 336
The styles apply and local storage works fine, but when I do a page refresh, the styles aren't applied to the links again. The values are still in local storage, but it's not showing visually on the page. How can I do a check to apply those styles to the values in the array that are in local storage.
$(function () {
var favorite = localStorage.getItem('favorite');
if (favorite !== null) {
favorite = JSON.parse(favorite) || [];
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
$(".favorites").click(function () {
var favorite = localStorage.getItem('favorite');
var petid = $(this).attr('data-petid');
var index;
favorite = JSON.parse(favorite) || [];
if ((index = favorite.indexOf(petid)) === -1) {
favorite.push(petid);
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
} else {
$(this).css('background-image', 'url(../assets/img/heart-full.svg)');
$(this).css('background-color', '#25aae3');
favorite.splice(index, 1);
}
localStorage.setItem('favorite', JSON.stringify(favorite));
});
});
Upvotes: 2
Views: 247
Reputation: 2896
you can always apply the styles on load / ready
$(function(){
var favorite = localStorage.getItem( 'favorite' );
if (favorite !== null){
favorite = JSON.parse(favorite);
...
(apply styles to all pet-ids in the favorites array)
}
});
EDIT 8/22 okay, I think you're going to want to edit your code to apply either style depending on whether the element is included in the favorite array, ie.
you may need to replace the lines
if (favorite !== null) {
favorite = JSON.parse(favorite) || [];
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
with
if (favorite !== null) {
favorite = JSON.parse(favorite) || [];
$(".favorites").each(function(ix,el){
var petid = $(this).attr("pet-id");
if(favorite.indexOf(petId) === -1){
$(this).css('background-image', 'url(../assets/img/heart-full.svg)');
$(this).css('background-color', '#25aae3');
}else{
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
}
This code applies one style if it is in the favorite array and another style if it is missing from the array.
Also, to address the question in the comment, you can apply multiple css styles in one line.
$(domelement).css({ "background-color": "#fefefe", "background=image": "url(../assets/img/heart-red.svg" });
This notation allows you to move the css arrays into reusable properites in your file, ie...
var avaliable = { "background-color": "#fefefe", "background=image": "..." };
var selected = { .... }
and then use them
$(domelement).css(available);
Upvotes: 1