Tell us what’s happening:
My heartBtnClicked function is giving a false statement the first time a button is clicked, but working correctly every other time it is clicked. I’m not really sure why this is happening or how to fix it.
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Favorite Icon Toggler</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Art Supplies</h1>
<div class="section">
<ul class="item-list">
<li>120 gm paper <button class="favorite-icon">♡</button></li>
<li>Watercolor Set <button class="favorite-icon">♡</button></li>
<li>Lead pencil 6B <button class="favorite-icon">♡</button></li>
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
/* file: styles.css */
.filled {
color: red;
}
/* file: script.js */
const heartButtons = document.querySelectorAll(`.favorite-icon`);
function heartBtnClicked(button) {
console.log("heartBtnClicked")
console.log(button)
console.log(!button.hasAttribute("class", "filled"))
// vv Works only if selected button has been clicked at least once.
if (!button.hasAttribute("class", "filled")) {
button.setAttribute("class", "filled")
button.innerHTML = `❤`;
console.log("Was not filled")
} else {
button.removeAttribute("class", "filled")
button.innerHTML =`♡`;
console.log("Was filled.")
}
}
heartButtons.forEach(function(btn) {
btn.addEventListener(`click`, () => heartBtnClicked(btn) )
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36
Challenge Information:
Build a Favorite Icon Toggler - Build a Favorite Icon Toggler