I want to change the colors of the body and text as you can see in my CSS styling. When I am trying to change the color of the theme via javascript, I am unable to complete this task.
<!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>Tutorial</title>
<style>
body{
font-family: tahoma;
font-size: 1.2em;
}
div#wrapper{
margin: 50px auto 0px auto;
width: 80%;
}
div#wrapper > div#button{
display: inline-block;
line-height: 60px;
padding: 0 30px;
border-radius: 25px;
cursor: pointer;
}
.black{
color: white;
background-color: black;
}
.white{
color: black;
background-color: white;
}
</style>
</head>
<body id="body">
<div id="wrapper">
<div id="button" >Click & Change Color</div>
<div id="content">
<h1>Muhammad Ahmad</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum, ad aperiam. Dolores itaque obcaecati iusto aliquid fuga, ad vel magnam adipisci sapiente voluptas, distinctio hic reprehenderit laudantium natus assumenda labore.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum, ad aperiam. Dolores itaque obcaecati iusto aliquid fuga, ad vel magnam adipisci sapiente voluptas, distinctio hic reprehenderit laudantium natus assumenda labore.</p>
</div>
</div>
<script>
var body = document.getElementById("body");
var button = document.getElementById("button");
button.onclick = function () {
if(body.className == "black"){
body.className = "white";
button.className = "black";
}else{
body.className = "black";
button.className = "white";
}
}
</script>
</body>
</html>
I also tried using external js and changing my CSS attributes but it's not working perfectly. The code is showing the same result. It will be great if you please help me to figure out this problem. Thanks!
CodePudding user response:
There is no problem in your code. It's working as expected.
Here is the working codepen: "https://codepen.io/gdsteve/pen/yLKKLzK"
CodePudding user response:
There is no error on your code it run perfectly on my system.
CodePudding user response:
I see no problem, maybe refresh your page. Also you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event to be sure the dom has been created before doing any changes to it.
CodePudding user response:
Your codes are working fine. You can make the codes simpler by toggling classlist. Either way works, your choice.
var body = document.getElementById("body");
var button = document.getElementById("button");
button.addEventListener("click", function() {
body.classList.toggle("black");
button.classList.toggle("white");
});