I’m trying to build a card navigation feature in JavaScript where clicking on a card displays its content in a hiddenCard element, and I can navigate between cards using left and right arrow buttons.
Selecting Cards and the Hidden Card:
var cards=document.querySelectorAll(".card");
var hiddenCard=document.querySelector(".card_hidden")
var currntIndex=0;
Adding Click Event to Each Card:
for (var i = 0; i < cards.length; i++) {
cards[i].addEventListener("click", function () {
currntIndex = Array.from(cards).indexOf(this);
var image = this.querySelector("img");
var title = this.querySelector(".title p");
hiddenCard.innerHTML = `
<p>${title.textContent}</p>
<img src=${image.src}>
<i class="fa-solid fa-arrow-left pre"></i>
<i class="fa-solid fa-arrow-right next"></i>
`;
hiddenCard.style.display = "block";
console.log(hiddenCard);
arrows();
});
}
Adding Navigation with Arrows:
function arrows() {
document.querySelector(".pre").addEventListener("click", function () {
if (currntIndex > 0) {
currntIndex--;
showIndex(currntIndex);
}
});
document.querySelector(".next").addEventListener("click", function () {
if (currntIndex < cards.length - 1) {
currntIndex++;
showIndex(currntIndex);
}
});
}
Updating the Hidden Card:
function showIndex(currntIndex) {
var imagIndex = cards[currntIndex].querySelector("img");
var titleIndex = cards[currntIndex].querySelector(".title p");
hiddenCard.innerHTML = `
<p>${titleIndex.textContent}</p>
<img src=${imagIndex.src}>
<i class="fa-solid fa-arrow-left pre"></i>
<i class="fa-solid fa-arrow-right next"></i>
`;
}
The hiddenCard displays correctly when I click on a card. However, when I use the arrow buttons, the hiddenCard content doesn’t update, or the navigation doesn’t work as expected.
2
Answers
You are calling
arrows
inside each of your event, so if you have 100 pictures, then you’ll assign 100 pre and next click event handlers, so clicking on pre or next will not only execute once, but many times. I have hidden cards for this example, feel free to change it however you please.Recommend that you implement a single event handler which takes advantage of event bubbling. Create the event handler on the parent element, and inspect the target (which is passed to the handler in the Event object) to determine which arrow or card was clicked.