How to change the text color in JavaScript on button click

How to change the text color in JavaScript:

In this post, we will learn how to change the color of a text in JavaScript. We will create one small html-css-js project, that will contain only one button and clicking on that button will change the color of a text.

Property to change:

We need to change the color property of a component. In this example, we will change the color of a p or paragraph component.

Example program:

Create one index.html file with the below content:

<!DOCTYPE html>
<html>

<head>
    <title>Change Color in JS</title>
</head>

<body>
    <button id="toBlue">Blue</button>
    <button id="toGreen">Green</button>
    <button id="toRed">Red</button>
    <div>
        <p id="output_text">Click the button to change the color.</p>
    </div>
    <script>

        document.getElementById("toBlue").onclick = function () {
            document.getElementById("output_text").style.color = 'blue';
        }

        document.getElementById("toGreen").onclick = function () {
            document.getElementById("output_text").style.color = 'green';
        }

        document.getElementById("toRed").onclick = function () {
            document.getElementById("output_text").style.color = '#FF0000';
        }

    </script>
</body>

</html>

Output:

Open this file in your favorite browser. It will show one text line with three buttons as like below:

js change text color

If you click on any of these buttons, it will change the color of the text.

Explanation:

Here,

  • The script tag holds the javascript part.
  • Each button has one id. All are different. Using document.getElementbyId in the JavaScript, we are accessing a specific button and we are adding one onclick listener. It means the function will be run if the user clicks on that element.
  • Now, inside the function, we are changing the color of the text. The text or p component also has one id. We are changing the style.color of the p component inside each function.
  • Each function invocation changes the color differently. We can pass the color names, or we can pass the hex value. Not all colors are defined, and the browser will not understand every name. So, it is a good practice to pass hexadecimal value instead of its name.

You might also like: