DEV Community

Mohana Kumar
Mohana Kumar

Posted on

🔴🔵 Color Toggle Using Button in HTML, CSS, and JavaScript

Introduction

This program shows how to change the color of a heading (<h1>) between red and blue when a button is clicked using JavaScript.


Code

<!DOCTYPE html>
<html>
<head>
  <style>
    .red {
      color: red;
    }

    .blue {
      color: blue;
    }
  </style>
</head>
<body>

<h1 id="title" class="red">Hello</h1>

<button onclick="toggleColor()">Change Color</button>

<script>
  function toggleColor() {
    const el = document.getElementById("title");
    el.classList.toggle("red");
    el.classList.toggle("blue");
  }
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How It Works

1. HTML

  • <h1> displays the text Hello
  • It starts with class red
  • A button is used to trigger the color change

2. CSS

  • .red → sets text color to red
  • .blue → sets text color to blue

3. JavaScript

  • getElementById("title") selects the <h1>
  • classList.toggle() switches classes:

    • removes current color
    • adds the other color

Output Behavior

  • Initially → 🔴 Red
  • Click button → 🔵 Blue
  • Click again → 🔴 Red

Conclusion

This is a simple example of:

  • DOM manipulation
  • Event handling
  • Using CSS classes with JavaScript

It helps beginners understand how web pages become interactive.


Top comments (0)