Changing Button Background Color on Click in HTML, CSS, and JavaScript

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

Photo by Pixabay

In the example, I’m showing a button with a blue background color. When the button is clicked, the background color changes to green.

The HTML code to display the button is as follows.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <button class="custom-button" onclick="changeColor()">Click Me</button>
</body>
</html>

I add style to the button using CSS

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

Next, I provide the JavaScript code that changes the button’s background color from blue to green when clicked.

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

Finally, I display the complete code and the result.

<!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="changeColor()">Click Me</button>

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

I hope this is helpful. Have a great day!

Leave a Comment