Currently, I am working on implementing an Add to Favorite feature. When I click on an icon, the breed next to that icon gets added to the likes array. I have created a renderLikes function to display the contents of the array on the screen. However, only one breed appears because of the elements.favorite.innerHTML='' part. If I remove that section, the entire array keeps getting added to the DOM tree whenever I click on an icon. Is there a way to render each item in the array individually like
item
,item2
, and so forth?Another issue I encountered is that sometimes when I click on an icon, it adds an empty element to the array. How can I prevent this problem from occurring?
<!DOCTYPE html>
<html lang="en">
<head>
<style>
ul {
list-style: none;
line-height: 1.6;
}
.icon {
display: inline-block;
width: 1em;
height: 1em;
stroke-width: 0;
stroke: currentColor;
fill: currentColor;
vertical-align: middle;
cursor: pointer;
transition: transform .3s;
transform: scale(0.8);
}
.icon:hover {
transform: scale(1.6) rotate(-15deg);
}
.icon-fill {
fill: red;
}
</style>
<title>Like Button Practice</title>
</head>
<body>
<ul class="list"></ul>
<h2>My Favorite Dogs</h2>
<div class="favorite">
</div>
<script>
const data = [
{
"breed": "Beagle",
"characteristics": "playful"
},
{
"breed": "Golden Retriever",
"characteristics": "calm"
},
{
"breed": "Corgi",
"characteristics": "bright"
},
{
"breed": "Goldendoodle",
"characteristics": "gentle"
},
{
"breed": "Labrador Retriever",
"characteristics": "loyal"
},
]
const elements = {
"icon": document.querySelectorAll('svg'),
"dom": document.querySelector('.list'),
"favorite": document.querySelector('.favorite')
}
const likes = [];
// Render method
function test() {
data.map(item => {
renderList(item.breed);
return item.breed;
})
};
test();
function renderList(dog) {
const markup = `
<li id="${dog}">
<svg class="icon icon-heart-outlined"><use xlink:href="icon/sprite.svg#icon-heart-outlined"></use></svg>
${dog}
</li>
`;
elements.dom.insertAdjacentHTML('beforeend', markup);
}
function renderLikes(item) {
const markup = `
<p>${item}</p>
`;
elements.favorite.innerHTML = '';
elements.favorite.insertAdjacentHTML('beforeend', markup);
}
elements.dom.addEventListener('click', e => {
const id = e.target.parentNode.id;
if (e.target.matches('.icon, .icon *')) {
// If (Beagle, Golden Retriever... does not exist in likes array, it returns -1)
const index = likes.indexOf(e.target.parentNode.id);
if (index === -1) {
likes.push(id);
console.log(likes);
likes.forEach(function( value ) {
console.log( value );
renderLikes(value);
});
} else {
likes.splice(index, 1);
}
}
});
</script>
</body>
</html>