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.