Why do multiple cards open simultaneously when clicking on a single card in my HTML/CSS/JavaScript setup?

35 Views Asked by At

First off - rookie coder here, with little experience. I have a web page containing multiple cards, each representing a museum exhibit. Upon clicking on a card, I want only that specific card to expand and show additional information, while the others remain closed. However, I'm encountering an issue where clicking on one card opens both that card and another card simultaneously, while not displaying the text on the inactive one.

HTML:

<div id="museum-container">
  <!-- Museum 1: Harmony Through Time -->
  <div class="museum-card" onclick="toggleMuseum(this)">
    <img src="music_museum.jpg" alt="Harmony Through Time" class="museum-image">
    <div class="museum-name">harmony through time</div>
    <div class="museum-description">Explore the evolution of music through the ages.</div>
    <button class="start-button" onclick="startMuseum('harmony through time')">Start</button>
  </div>

  <!-- Museum 2: Time Capsule -->
  <div class="museum-card" onclick="toggleMuseum(this)">
    <img src="time_capsule.jpg" alt="time capsule" class="museum-image">
    <div class="museum-name">time capsule</div>
    <div class="museum-description">Embark on a journey through historical artifacts and moments.</div>
    <button class="start-button" onclick="startMuseum('time capsule')">Start</button>
  </div>
</div>

JavaScript:

function toggleMuseum(card) {
    var isActive = card.classList.contains('active');
  
    // Remove active class from all cards
    document.querySelectorAll('.museum-card').forEach(function (element) {
      element.classList.remove('active');
    });
  
    // Toggle active class only on the clicked card
    if (!isActive) {
      card.classList.add('active');
    }
}

CSS:

.museum-card.active .museum-description,
.museum-card.active .start-button {
  display: block;
}

.active {
  background-color:rgb(177, 134, 70);
}

I've tried using an alert function to find where the error is, but no matter where I put it, it wouldn't even appear.

1

There are 1 best solutions below

1
Erik Qoqobelyan On

To prevent this, you can stop event propagation using event.stopPropagation() in your toggleMuseum function. Here's how you can modify your JavaScript code:

function toggleMuseum(card, event) { event.stopPropagation(); // Stop event propagation

var isActive = card.classList.contains('active');

// Remove active class from all cards
document.querySelectorAll('.museum-card').forEach(function (element) {
    element.classList.remove('active');
});

// Toggle active class only on the clicked card
if (!isActive) {
    card.classList.add('active');
}

}