Menu
Coddy logo textTech

Temas claro y oscuro

Parte de la sección JavaScript in Action del Journey de HTML de Coddy — lección 16 de 27.

Implementar un interruptor de tema oscuro/claro es una característica común en los sitios web modernos. Aprendamos cómo crear un selector de temas sencillo usando JavaScript.

Primero, crea un botón que alternará entre temas:

<button id="themeToggle">Theme Toggle</button>

A continuación, añadamos un poco de CSS básico para nuestros temas claro y oscuro:

<style>
  :root {
    --background-color: #ffffff;
    --text-color: #333333;
  }
  
  body {
    background-color: var(--background-color);
    color: var(--text-color);
    transition: background-color 0.3s, color 0.3s;
  }
  
  .dark-theme {
    --background-color: #222222;
    --text-color: #f5f5f5;
  }
</style>

Ahora, vamos a añadir el JavaScript para alternar entre temas:


const themeToggle = document.getElementById('themeToggle');
  
themeToggle.addEventListener('click', function() {
  document.body.classList.toggle('dark-theme');
});

Cuando haces clic en el botón, se alterna la clase 'dark-theme' en el elemento body.

challenge icon

Desafío

Fácil

Dentro del escuchador de eventos click del botón, añade código para alternar la clase "dark-mode" en el elemento body.

Pruébalo tú mismo

<!DOCTYPE html>
<html>
<head>
  <title>Dark/light themes</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Hygge ✨</h1>
    <button id="themeToggle" class="toggle-btn">Toggle Theme</button>
  </header>

  <main>
    <section class="intro">
      <img src="https://images.unsplash.com/photo-1519710164239-da123dc03ef4?auto=format&fit=crop&w=1350&q=80" alt="Cozy hygge scene" class="hero-img">
      <p>
        <strong>Hygge</strong> is a Danish concept that embodies coziness, comfort, and a sense of well-being.  
        It’s about enjoying life’s simple pleasures — candles, warm drinks, good company, and soft blankets.
      </p>
    </section>

    <section class="philosophy">
      <h2>The Philosophy</h2>
      <p>
        Hygge is less about things and more about atmosphere and feelings.  
        It’s creating moments of calm, warmth, and togetherness — a way to nurture happiness in everyday life.
      </p>
    </section>

    <section class="origin">
      <h2>Where It Comes From</h2>
      <p>
        Originating from Denmark, hygge reflects the Danish culture’s deep appreciation for balance, comfort,  
        and community. It’s often credited as one of the reasons why Denmark consistently ranks among the  
        happiest countries in the world.
      </p>
    </section>
  </main>

  <footer>
    <p>☕ Embrace hygge in your daily life.</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 in Action