I'm trying to make the button work when the ratings are clicked. Otherwise I don't won't the button addEventListener to work
I did check if all the elements are correctly looped through using console.log. I didn't find any mistakes in my code
Code
"use strict";
const btn = document.querySelector(".btn");
const activeBtn = document.querySelector(".btn--active");
const cardFront = document.querySelector(".card__side--front");
const cardBack = document.querySelector(".card__side--back");
const ratingNum = document.querySelectorAll(".card__rating-num");
ratingNum.forEach((rating) => {
rating.addEventListener("click", () => {
btn.classList.add("btn--active");
});
});
activeBtn.addEventListener("click", () => {
cardFront.style.transform = "rotateY(-180deg)";
cardBack.style.transform = "rotateY(0)";
});
<div class="card__footer">
<div class="card__rating u-mbm">
<span class="card__rating-num">1</span>
<span class="card__rating-num">2</span>
<span class="card__rating-num">3</span>
<span class="card__rating-num">4</span>
<span class="card__rating-num">5</span>
</div>
<a href="#" class="btn">Submit</a>
</div>
You're trying to get activeBtn
before the button has been made active by clicking on one of the rating numbers. Since there's no active button yet, activeBtn
is null and you can't add an event listener to it.
Instead, add the event listener to btn
, and it can check whether it's active.
"use strict";
const btn = document.querySelector(".btn");
const activeBtn = document.querySelector(".btn--active");
const cardFront = document.querySelector(".card__side--front");
const cardBack = document.querySelector(".card__side--back");
const ratingNum = document.querySelectorAll(".card__rating-num");
ratingNum.forEach((rating) => {
rating.addEventListener("click", () => {
btn.classList.add("btn--active");
});
});
btn.addEventListener("click", (e) => {
if (e.target.classList.contains("btn--active")) {
console.log("Clicked on submit");
}
});
.btn {
color: grey;
}
.btn.btn--active {
color: black;
}
<div class="card__footer">
<div class="card__rating u-mbm">
<span class="card__rating-num">1</span>
<span class="card__rating-num">2</span>
<span class="card__rating-num">3</span>
<span class="card__rating-num">4</span>
<span class="card__rating-num">5</span>
</div>
<a href="#" class="btn">Submit</a>
</div>