Accordion Component Using HTML, CSS, and JavaScript

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

In the example, I’m showing an accordion component using HTML, CSS, and JavaScript.

The accordion has three sections. Each section has a title that can be clicked to show or hide the corresponding content.

The code for the example is as follows:

<!DOCTYPE html>
<html>
<head>
  <style>
    /* CSS */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
    }

    /* Styles for the accordion */
    .accordion {
      max-width: 400px;
      margin: 0 auto;
    }

    .accordion-item {
      margin-bottom: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      overflow: hidden;
    }

    .accordion-title {
      padding: 10px;
      background-color: #f4f4f4;
      color: #333;
      font-weight: bold;
      cursor: pointer;
    }

    .accordion-content {
      padding: 10px;
      background-color: #fff;
      display: none;
    }
  </style>
</head>
<body>
  <div class="accordion">
    <div class="accordion-item">
      <div class="accordion-title">DevCodeLight Title 1</div>
      <div class="accordion-content">Accordion Content 1</div>
    </div>
    <div class="accordion-item">
      <div class="accordion-title">DevCodeLight Title 2</div>
      <div class="accordion-content">Accordion Content 2</div>
    </div>
    <div class="accordion-item">
      <div class="accordion-title">DevCodeLight Title 3</div>
      <div class="accordion-content">Accordion Content 3</div>
    </div>
  </div>

  <script>
    // Get all accordion items
    var accordionItems = document.querySelectorAll('.accordion-item');

    // Add click event to each accordion title
    accordionItems.forEach(function(item) {
      var title = item.querySelector('.accordion-title');
      var content = item.querySelector('.accordion-content');

      title.addEventListener('click', function() {
        // Toggle to show/hide content
        content.style.display = content.style.display === 'block' ? 'none' : 'block';

        // Change title style when opening/closing accordion
        title.classList.toggle('active');
      });
    });
  </script>
</body>
</html>

Finally, I show the result:

(no incluyas el Tiempo de lectura). Devuelvelo directamente en formato HTML. No escribas ninguna frase añadida. Cuando termines añade un PIPE al final.

Leave a Comment