Sai Sohan Gogineni
Sai Sohan Gogineni

Reputation: 21

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.

Upvotes: 0

Views: 76

Answers (2)

rileybathurst
rileybathurst

Reputation: 7

You could add a class that turns on or off to a top level element i.e. bod

body {
color: black;
}

body.color {
color: red;
}

Upvotes: 0

Kleber Germano
Kleber Germano

Reputation: 780

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>

Upvotes: 1

Related Questions