Issue
I am using JavaScript and I am beginner. I want to change the background color using the button. And after that click again to change it back to the previous color. Here my code :
const cColor = document.getElementById("cColor");
cColor.onclick = function() {
document.body.style.backgroundColor = "salmon";
};
body {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Change Backgroud Color</h1>
<button type="button" id="cColor">Button</button>
<script src="script.js"></script>
</body>
</html>
Solution
It's easier with classNames but if you want to do it modifying the background color with js, here you have a possible solution:
const cColor = document.getElementById("cColor");
cColor.onclick = function () {
if (document.body.id === "active") {
document.body.id = "";
document.body.style.backgroundColor = "transparent";
} else {
document.body.id = "active";
document.body.style.backgroundColor = "salmon";
}
};
<!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" />
<title>Document</title>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<h1>Change Backgroud Color</h1>
<button type="button" id="cColor">Button</button>
<script src="script.js"></script>
</body>
</html>
With classname:
const cColor = document.getElementById("cColor");
cColor.onclick = function () {
document.body.classList.toggle("active");
};
<!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" />
<title>Document</title>
<style>
body {
text-align: center;
}
body.active{
background-color: salmon;
}
</style>
</head>
<body>
<h1>Change Backgroud Color</h1>
<button type="button" id="cColor">Button</button>
<script src="script.js"></script>
</body>
</html>
Answered By - mgm793
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.