Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading