Open In App

How to Change the Color of Button on Click ?

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, on a web page, when a user clicks a button it gets difficult to understand whether the button is clicked or not. In such cases, you can change the background color of the button to indicate that the button is clicked.

The below methods can be used to change background color of a button on click.

Using :active pseudo selector

We can change the color of a button when we click on it using the :active pseudo property of CSS. This property changes the color of the button when we click on the button.

Syntax:

selectedHTMLElement:active{
// CSS to change color
}

Example: The below code will explain the use of the :active pseudo property to change the color of a button on click.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, 
                                   initial-scale=1.0">
    <title>Document</title>

    <style>
        button {
            background-color: darkblue;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
        }

        button:active {
            background-color: rgb(36, 174, 96);
            transform: translateY(4px);
        }
    </style>
</head>

<body style="text-align: center;">
    <h1>
        Click the below button to change
        <br/>the backgroud color.
    </h1>
    <button>
        Click here
    </button>
</body>

</html>

Output:

fosiGIF

Using JavaScript

You can also use the addEventListener() method of JavaScript to add click event and change the color of the button to a particular button permanently.

Syntax:

 selectedHTMLElement.addEventListener('click', callbackFn);

Example: The below code will explain the use of JavaScript to change the color of a button on click.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        button {
            background-color: blue;
            color: white;
            padding: 10px 20px;
        }
    </style>
</head>

<body style="text-align: center;">
    <h1>
        Click the below button to change
        <br /> the color of it.
    </h1>
    <button>
        Click here
    </button>

    <script>
        const button =
            document.querySelector('button');
        button.addEventListener('click',
            () => {
                button.style.backgroundColor = 
                    "green";
            });
    </script>
</body>

</html>

Output:

fosiGIF



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads