Home > front end >  How do I program a javascript function to switch button colors back and forth?
How do I program a javascript function to switch button colors back and forth?

Time:11-03

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?

CodePudding user response:

<!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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related