'How to save activities for user HTML/JavaScript/jQuery
I made favorite buttons and if user clicks on it, it will save specific favorited item to a different page with LocalStorage
. Code works perfectly but now I want to save this activity for specific user. And I'm using "Login With Google" button. I can get users profile and name but now I want to save those favorited items. So basically I want to get rid of LocaStorage
. Here my code where I'm saving favorited items with LocalStorage
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/6b64e3f7bc.js" crossorigin="anonymous"></script>
</head>
<body>
<form action="favorites.html">
<p>A<i class="heart fa fa-heart-o" aria-hidden="true"></i></p>
<p>B<i class="heart fa fa-heart-o" aria-hidden="true"></i></p>
<p>C<i class="heart fa fa-heart-o" aria-hidden="true"></i></p>
<p>D<i class="heart fa fa-heart-o" aria-hidden="true"></i></p>
<p>E<i class="heart fa fa-heart-o" aria-hidden="true"></i></p>
<button href="favorites.html">Go</button>
</form>
<script>
$(function () {
const swapToggle = ($heart, toggle) => {
$heart.toggleClass("fa-heart-o", !toggle);
$heart.toggleClass("fa-heart", toggle);
};
const $hearts = $(".heart");
const toggleString = localStorage.getItem("togglesM");
const toggles = toggleString ? JSON.parse(toggleString) : $hearts.map(function () {
return $(this).hasClass('fa-heart')
}).get();
$hearts.each(function (i, elem) {
swapToggle($(this), toggles[i])
$(this).data("idx", i);
})
$('.heart').on('click', function () {
const idx = +$(this).data("idx");
toggles[idx] = !toggles[idx];
swapToggle($(this), toggles[idx])
localStorage.setItem("togglesM", JSON.stringify(toggles))
var favs = $('.heart.fa-heart').map((i, f) => `<p>${f.parentElement.innerHTML}</p>`).get().join('\n')
localStorage.setItem("paragraphValueMath", favs);
console.clear();
})
});
</script>
</body>
</html>
And this is my second(favorites) page:
<div id="favorites">
<!--FAVORITES HERE-->
</div>
<script>
if (localStorage.getItem("paragraphValueMath") == null) {
var para = document.createElement("p");
para.innerHTML = 'Empty... <div class="far fa-frown-open"></div>';
document.getElementById("favorites").appendChild(para);
} else {
document.getElementById("favorites").innerHTML = localStorage.getItem("paragraphValueMath");
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|