I have a fav-icon on each card (carrousel of gifs) that is display and hidden by button click.And I need that if the users clicks the fav icon stays active even if the page refresh. I'm guiding from this question show display:none div after refresh but my code is a little bit different (Vanilla JS and Template literals):
Section creating the template for every card
const loadData = (data) => {
let trendSection = document.querySelector('.card-container')
let content = ''
for (let i = 0; i < data.length; i++) {
content += `
<img class="image-card" src="${data[i].images.downsized.url}">
<div class="custom-overlay-icons">
<a type="button"><img class="image_on" src="assets/images/icon-fav.svg" onClick="likeCard('${[i]}')"><img id="fav-active${[i]}" src="assets/images/icon-fav-active.svg"></a>
//The display of fav-active img is none by default in CSS
</div>`
}
trendSection.innerHTML = content
}
Section to get the icon to change on click
window.likeCard = (index) => {
let image = document.getElementById('fav-active' + i)
if (!image.style.display || image.style.display === 'none') {
image.style.display = 'block'
localStorage.setItem('show');
} else {
image.style.display = 'none'
localStorage.removeItem('show');
}
}
Finnally, the problem, is that I dont know how and where to implement the function that the checks the state onLoad like they porpuse on the solution if I need the index variable, I got these:
window.onload = function(i) {
let show = localStorage.getItem('show');
if(show === 'true'){
document.getElementById('fav-active' + i).style.display = "block";
}
}
I don't know If I was clear but let me know if something does'nt make sense
From the MDN:
The setItem() method of the Storage interface, when passed a key name and value, will add that key to the given Storage object, or update that key's value if it already exists.
The Syntax:
storage.setItem(keyName, keyValue);
You are trying to store the show variable in the localStorage, but you didn't pass any keyValue to it. so in onload event handler, the show variable is undefined.
set the show item properly in likeCard event handler:
if (!image.style.display || image.style.display === 'none') {
image.style.display = 'block'
localStorage.setItem('show', true); // or false as your desire
} else {
image.style.display = 'none'
localStorage.removeItem('show', false); // or true as your desire
}
since the result of let show = localStorage.getItem('show') is only booleans (true/false), you can remove the comparison from the if block in the onload handler:
window.onload = function(event) {
let show = localStorage.getItem('show');
if(show) { // ------> if (true) / if(false)
document.getElementById('fav-active').style.display = "block";
}
}