Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
How do I program a javascript function to switch button colors back and forth?

I'm trying to turn a blue button red by using an onclick, but then I also want the button to turn back to being blue after clicking again using the same onclick function.

How would I do this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .round {
            border-radius: 5px;
            color: aliceblue;
        }
        .blue {
            background-color: blue;
        }
        .red {
            background-color: red;
        }
    </style>
</head>
<body>
    <button id="btn" class="round blue" onclick="clickBtn()">button</button>
    <script>
        function clickBtn() {
            let btn = document.getElementById('btn')
            if(btn.classList.contains('blue')) {
                btn.classList.remove('blue')
                btn.classList.add('red')
            } else {
                btn.classList.remove('red')
                btn.classList.add('blue')
            }
        }
    </script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Report

0

You can give the button a default background color, then add a click event listener to it which toggles a class that applies a different background color:

document.querySelector('button').addEventListener('click', function(){ this.classList.toggle("red") })
button{
  background-color:green;
}
.red{
  background-color:red;
}
<button>Hello World!</button>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!