Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  7] [ 1]  / answers: 1 / hits: 17922  / 6 Years ago, thu, july 12, 2018, 12:00:00

I am creating a song book app with 'add to favorite' button. i have song1.html song2.html and favorite.html.



in song1.html, when add to favorite button is clicked. i am storing the link to that song in local storage.



This is my song1.html





<!DOCTYPE html>
<html>
<body>



<button onclick=mySongOne()>add to favorite</button>





<script>
function mySongOne() {
localStorage.setItem(favsong, <a href='https://www.song1.com'><h1>song1</h1></a>);
}


</script>

</body>
</html>





in song2.html, when add to favorite button is clicked. i am storing the link of the second song in local storage.



song2.html





<!DOCTYPE html>
<html>
<body>



<button onclick=mySongTwo()>add to favorite</button>



<script>
function mySongTwo() {
localStorage.setItem(favsong, <a href='https://song2.com'><h1>song2</h1></a>);
}


</script>

</body>
</html>





now i have a favorite.html for listing my favourite songs. and favourite.html will retrieve the links that i stored in local storage.



favorite.html





<!DOCTYPE html>
<html>
<body onload=myFunction()>

<div id=result></div>



<script>
function myFunction() {
document.getElementById(result).innerHTML = localStorage.getItem(favsong);
}

</script>

</body>
</html>





Now i want to show both song 1 and song 2 in favorite.html.
but only song 2 is displayed in favourite.html. How to accomplish this.


More From » html

 Answers
12

If you really need to append data to the same LocalStorage key, there is no built-in append function.



However, you can use a custom function, for instance the one proposed in this answer: https://stackoverflow.com/a/7680123/2446264, and get the following code to do what you want:





<!DOCTYPE html>
<html>
<body>

<div id=result></div>

<script>
// Check browser support
if (typeof(Storage) !== undefined) {
// Store
localStorage.setItem(list, <h1>John<h1>);
appendToStorage(list, <h2>David<h2>);

// Retrieve
document.getElementById(result).innerHTML = localStorage.getItem(list);
} else {
document.getElementById(result).innerHTML = Sorry, your browser does not support Web Storage...;
}

function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = ;
localStorage.setItem(name, old + data);
}
</script>

</body>
</html>




[#53998] Monday, July 9, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carolyn

Total Points: 618
Total Questions: 119
Total Answers: 86

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;