简体   繁体   中英

How do I store my selected favorites in localstorage? (javascript)

I have code for displaying birds, images of the birds and tags. There is an option to favorite certain birds with a favorite button. I want to store the birds that are selected as a favorite in localstorage, how do I do this? When I try to store the favBtn.value it won't display anything. Thanks in advance.

EDIT: I also shared my html code now

 window.addEventListener('load', init); const cardsContainer = document.querySelector('#cards'); const aside = document.querySelector('#wrapper aside'); /* array with birds */ const birds={ 'Koolmees':{ src:'https://source.unsplash.com/1600x900/?koolmees', tags:'rotterdam, koolmees, kleine vogel' }, 'Specht':{ src:'https://source.unsplash.com/1600x900/?specht', tags:'specht, nijmegen, kleine vogel' }, 'kerkuil':{ src:'https://source.unsplash.com/1600x900/?snowowl', tags:'uil, eindhoven, grote vogel, roofvogel' } }; /* if there is no `figcaption` below the image it will add the caption and assign the `tags` text which is assigned to the image as a dataset attribute */ const clickhandler=function(e){ let fig=e.target.parentNode.querySelector('figcaption'); if( fig==null ){ fig=document.createElement('figcaption'); fig.textContent=this.dataset.tags e.target.parentNode.appendChild( fig ); }else{ e.target.parentNode.removeChild(fig) } aside.textContent=fig==null? '': this.dataset.tags; } /* this function changes te color in the button */ function setColor(el, color) { if (el.value == 0) { el.style.backgroundColor = "#FFFFFF" el.value = 1; } else { el.style.backgroundColor = "#7FFF00" el.value = 0; } } function init(){ document.getElementById('cards').querySelectorAll('.card').forEach( card => { card.addEventListener('click',clickhandler ); }); } /* adding elements to cards */ function addCard(birdImage, birdName, birdTags){// now takes 3 arguments let item = document.createElement('flex-item'); item.classList.add('card'); item.dataset.tags=birdTags; //assign the tags as a dataset atttribute cardsContainer.appendChild(item) let favBtn = document.createElement('button') favBtn.innerText = '❤' favBtn.value = 0 favBtn.setAttribute('onclick', 'setColor(this, "#101010")') favBtn.classList.add('fav-btn') item.appendChild(favBtn) let img = document.createElement('img') img.src = birdImage; img.title=birdTags; // tags also assigned for the img title item.appendChild(img) let name = document.createElement('div') name.innerText = birdName item.appendChild(name) } /* Using the `object.keys` method allows us to quickly iterate through each sub-object. The `key` is the bird name. */ function addCards(){ Object.keys( birds ).forEach( key => { let bird=birds[ key ]; addCard( bird.src, key, bird.tags ) }) } addCards()
 <,doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="description" content="magazine zonder fetch"> <meta name="keywords" content="HTML, CSS, JavaScript"> <meta name="author" content="Micha van der Willigen"> <meta name="viewport" content="width=device-width, user-scalable=no. initial-scale=1,0. maximum-scale=1,0. minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <title>Bird magazine</title> </head> <body> <div id='wrapper'> <header><p1>Vogel magazine voor vogelspotters.</p1></header> <main> <p> <!-- with these buttons you can set the website in full screen --> <button class="start" id="startFull">Start fullscreen on the whole page</button> <button id="exit">Exit fullscreen</button> </p> <!-- here the cards with the birds will be displayed --> <flex-container id="cards"> </flex-container> </main> <aside>Click on a bird to display the tags!</aside> <footer><p>Website door Micha van der Willigen</p></footer> </div> <script src="js/main.js"></script> <script src="js/fullscreen.js"></script> </body> </html>

I'd use a couple of functions to load and to write to local storage

const loadBird = () => {
    if (localStorage['favouriteBird']) 
        // If a saved bird exists
        savedBird = JSON.parse(localStorage['favouriteBird'])
    else 
        // No saved birds
        savedBird = {}
}

const saveBird = () => {
    localStorage['favouriteBird'] = JSON.stringify(favouriteBird)
}

To use in your code, just add loadBird() into the init function and also add a favouriteBird variable at the top of your script.

Whenever a favourite bird is updated, just call the saveBird() function

Just change the variable names to whatever you want, and also add an if statement to check if savedBird is null or undefined and if it is just define it as the starting bird.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM