Menu
Coddy logo textTech

Menús desplegables

Parte de la sección JavaScript en Acción del Journey de HTML de Coddy. Lección 15 de 27.

Los menús desplegables son componentes de la interfaz de usuario que muestran opciones adicionales cuando se activan. Se utilizan comúnmente en la navegación para organizar el contenido sin ocupar demasiado espacio.

Primero, creemos la estructura HTML para un menú desplegable básico:

<div class="dropdown">
  <button class="dropdown-toggle">Menu</button>
  <div class="dropdown-menu">
    <a href="#">Option 1</a>
    <a href="#">Option 2</a>
    <a href="#">Option 3</a>
  </div>
</div>

Ahora, añadamos el JavaScript para alternar la visibilidad del menú desplegable:

// Get the dropdown toggle button
const dropdownToggle = document.querySelector('.dropdown-toggle');

// Get the dropdown menu
const dropdownMenu = document.querySelector('.dropdown-menu');

// Add click event listener to the toggle button
dropdownToggle.addEventListener('click', function() {
  // Toggle the 'show' class on the dropdown menu
  dropdownMenu.classList.toggle('show');
});

Por último, añade algo de CSS básico para ocultar/mostrar el menú desplegable:

.dropdown-menu {
  display: none;
}

.dropdown-menu.show {
  display: block;
}

Cuando hagas clic en el botón "Menu", aparecerá el menú desplegable. Si haces clic en él nuevamente, el menú se ocultará.

challenge icon

Desafío

Fácil

Crea un menú desplegable que se muestre u oculte cuando se haga clic en un botón.

Pasos:

  1. En HTML:
    • Añade un atributo onclick al botón que llame a una función llamada toggleDropdown al hacer clic
  2. En JavaScript:
    • Crea una función llamada toggleDropdown
    • Dentro de la función, alterna la clase "show" en el elemento con el ID “myDropdown”

Pruébalo tú mismo

<!DOCTYPE html>
<html>
<head>
  <title>Save the Forests</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Save the Forests</h1>
    <p>Even planting one or two trees makes a difference.</p>
  </header>

  <div class="dropdown">
    <button class="dropbtn">Learn More ▼</button>
    <div id="myDropdown" class="dropdown-content">
      <a href="#">Why forests matter</a>
      <a href="#">How to grow a tree</a>
      <a href="#">Community projects</a>
    </div>
  </div>

  <main>
    <section>
      <h2>Why Trees Are Important</h2>
      <p>
        Forests clean our air, give us oxygen, and are home to countless animals.  
        Each tree you plant helps fight climate change and supports life on Earth.
      </p>
    </section>
    <section>
      <h2> Start Small</h2>
      <p>
        Don’t wait for a big change. Start with just one or two trees in your yard or community.  
        Your small action inspires others!
      </p>
    </section>
  </main>

  <footer>
    <p> Together we can make the planet greener.</p>
  </footer>

  <script src="script.js"></script>
</body>
</html>
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de JavaScript en Acción

Practica por tu cuenta: Playground de Web