<!DOCTYPE html>
<
html
>
<
head
>
<
style
>
button {
background-color: green;
color: white;
padding: 10px 24px;
font-size: 18px;
border: none;
font-weight: bold;
transition: all 0.4s;
margin: 300px;
}
.active {
background-color: black;
}
</
style
>
</
head
>
<
body
>
<
button
>GeeksforGeeks</
button
>
<
script
>
// Select the button on which the
// class has to be toggled
const btn = document.querySelector("button");
// Select the entire HTML document
const html = document.querySelector("html");
// Add an event listener for
// a click to the button
btn.addEventListener("click", function (e) {
// Add the required class
btn.classList.add("active");
});
// Add an event listener for a
// click to the html document
html.addEventListener("click", function (e) {
// If the element that is clicked on is
// not the button itself, then remove
// the class that was added earlier
if (e.target !== btn)
btn.classList.remove("active");
});
</
script
>
</
body
>
</
html
>