Home > Software design >  How can I create one button to change the color of a text and then back to the default color?
How can I create one button to change the color of a text and then back to the default color?

Time:03-16

I have this code here that I used to create two buttons to change the color (purple) and the other one to change it back to the default color (black). But I want to create only one button that does both, change the color, and then back to the default color in this case black. How can I do that? Thanks!

<body>
<h1>Welcome to my first Web App!</h1>

<p>This web app will change the color of the text below:</p>
<h3 id="color-change">My color will change!</h3>
<button onclick="changeColor()">Change color</button>
<button onclick="defaultColor()">Default color</button>

<script !src="">
    function changeColor(){
        var element = document.getElementById("color-change");
        element.className = "myClass";
    }

    function defaultColor(){
        var element = document.getElementById("color-change");
        element.className = "defaultCol";
    }
</script>
</body>

CodePudding user response:

You can use .toggle() to toggle the class on the button click. What we do is get the classList of the element and toggle myClass on each click

var element = document.getElementById("color-change");
element.classList.toggle('myClass');

function changeColor() {
  var element = document.getElementById("color-change");
  element.classList.toggle('myClass')
}
.myClass {
  color: red;
}
<h1>Welcome to my first Web App!</h1>

<p>This web app will change the color of the text below:</p>
<h3 id="color-change">My color will change!</h3>
<button onclick="changeColor()">Toggle color</button>

  • Related