Create a button that changes element text color on click in JavaScript

Create a button that changes element text color on click in JavaScript

We have to create a button in HTML which will change the text color of the heading on click.

We will be going to see how to do this in JavaScript step by step.

Step 1 - Create a HTML structure

In HTML, we will create one H1 tag and one Button.

<!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">
    <link rel="stylesheet" href="./style.css">
    <title>Change Heading Color</title>
</head>
<body>
    <h1 id="heading-element">Change My Color</h1>

    <button id="red-btn">Red</button>

    <script src="./app.js"></script>
</body>
</html>

In Live Server it would look like this:

blog3-img1.png

Step 2 - Accessing the heading and button elements in JavaScript using Query Selectors.

const headingElement = document.querySelector("#heading-element");
const redBtn = document.querySelector("#red-btn");

Nothing changes on the Live Server.

Step 3 - Adding an event listener to the button.

We will add an event listener to the button which will run the function on "click".

redBtn.addEventListener("click", changeMyColor);

The first argument, "click" denotes that an event should occur when the user clicks the button, and the second argument is the name of the function (that we will create in our next step) which will run after the user clicks the button.

Step 4 - Creating "changeMyColor()" function.

This is the main part of the tutorial. We will create "changeMyColor()" function in which we will change the text color property of heading using ".style.color" attribute.

function changeMyColor(){
    headingElement.style.color = "red";
}

Here is the complete JavaScript code we wrote till now:

const headingElement = document.querySelector("#heading-element");
const redBtn = document.querySelector("#red-btn");

function changeMyColor(){
    headingElement.style.color = "red";
}

redBtn.addEventListener("click", changeMyColor);

Step 5 - Checking if our code is working or not.

Before Clicking the "Red" button:

blog3-img1.png

After Clicking the "Red" button:

blog3-img2.png

As you can see, our code works completely fine. Hope you learned something new from this tutorial.

Have a Good Day!