I have this function:
const btns = document.querySelectorAll('#btn')
const items = document.querySelector('#item')
btns.forEach(btn => {
btn.addEventListener('click', (e) =>{
const item = e.currentTarget.parentElement
item.classList.toggle('strike')
})
})
Now, how can I save classList.toggle('strike')
to localStorage?
I tried like this:
window.addEventListener('DOMContentLoaded',() => {
const listItems = items.map(item => {
return `
<ul>
<li id='item'>${item}</li>
<button id='btn'>Click</button>
</ul>
`
})
content.innerHTML = listItems.join(' ')
const btns = document.querySelectorAll('#btn')
btns.forEach(btn => {
btn.addEventListener('click', (e) =>{
if(btn) {
const item = e.currentTarget.parentElement
const wasToggled = localStorage.getItem('strike') === 'true'
localStorage.setItem('strike', !wasToggled)
item.classList.toggle('strike', !wasToggled)
}
})
})
window.onload = () => {
items.classList.toggle('strike', localStorage.getItem('strike') == 'true')
}
However, it was kinda slow and there are some things I don't understand from this code that I found somewhere:
Why has the
true
be a string rather than a boolean? When I typetrue
as a boolean rather than a string why it doesn't work is there any difference betweentrue
and'true'
? When the page is refreshed it saves the classList to the first item in the list, why is that?
Sorry, I'm a noob...