Skip to content

Is there anyway to create a button in html which when clicked, turns on the css?

For example, Imagine a black and white page, and then when you click the button, the page refreshes, giving you the same page but with css? Right now the only way I can think of doing this is with 2 different pages, but it would be nice to to do it with one page.

Answer

If you just want to change the button, you could add a class of CSS using JS when the button is clicked like this:

let btn = document.querySelector('#myButton2');
btn.addEventListener('click', (e)=>{
e.target.classList.toggle('addClassGreen');
});
.myButtons{
border-radius:5px;
padding:20px; 
color:#fff;
background:#666;
}
#myButton1:hover{
background:purple;
}
#myButton1:active{
background:red;
}
.addClassGreen{
background:green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class='myButtons' id='myButton1'>Temporarily reaction with CSS</button>
<button class='myButtons' id='myButton2' >Adding class with JS</button>
</body>
</html>