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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
<!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>
Method 2
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>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0