Cambiar fondo de color de un botón al pulsarlo en HTML, CSS y JavaScript

Tiempo de lectura: 2 minutos
Foto de Pixabay

En el ejemplo muestro un botón con el fondo de color azul, al pulsar el botón, el fondo cambia de color al verde.

El código para mostrar el botón en html es el siguiente.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <button class="custom-button" onclick="cambioColor()">Haz clic</button>
</body>
</html>

Le añado estilo al botón con CSS

<style>
    /* CSS */
    .custom-button {
      background-color: blue;
      color: white;
      padding: 10px;
      border: none;
      cursor: pointer;
    }
    
  </style>

A continuación hago el código de acción que al pulsar el botón modifica su fondo de color azul a verde usando JavaScript

  <script>
    // JavaScript
    function cambioColor() {
      var button = document.querySelector('.custom-button');
      button.style.backgroundColor = 'green';
    }
  </script>

Por último muestro el código completo y el resultado.

<!DOCTYPE html>
<html>
<head>
  <style>
    /* CSS */
    .custom-button {
      background-color: blue;
      color: white;
      padding: 10px;
      border: none;
      cursor: pointer;
    }
    
  </style>
</head>
<body>
  <button class="custom-button" onclick="cambioColor()">Haz clic</button>

  <script>
    // JavaScript
    function cambioColor() {
      var button = document.querySelector('.custom-button');
      button.style.backgroundColor = 'green';
    }
  </script>
</body>
</html>

Espero que les sirva de ayuda, feliz día!

Deja un comentario