I attempted to use DOM manipulation to change the page background color and div background color by utilizing getElementById and onclick methods. I wrote some code to make this happen, but unfortunately, it did not work as expected.
Can anyone identify what's causing the issue in my code?
Any suggestions on how to fix it?
HTML
<html lang="en">
<head>
<mate charset="utf-8" />
<title>change color</title>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<div id="test">
<a href="javascript:void(0);" id="bodyColor">change body background-color</a>
<a href="javascript:void(0);" id="divColor">change div background-color</a>
</div>
<script src="test.js"> </script>
</body>
</html>
CSS
body *{
margin: 0;
padding: 0;
}
a{
display: block;
color: white;
background-color: red;
width: 200px;
text-align: center;
font-weight: bold;
margin: 150px auto;
text-decoration: none;
}
#test{
border: 1px solid black;
width: 500px;
margin: 0 auto;
}
JavaScript
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function bodyBackgroundColor() {
var color = document.getElementById('bodyColor');
color.onclick = function(){
body.style.backgroundColor = "red";
}
}
function divBackgroundColor() {
var color = document.getElementById('divColor');
var divColor = document.getElementById('test');
color.onclick = function(){
divColor.backgroundColor = "red";
}
}
addLoadEvent(bodyBackgroundColor);
addLoadEvent(divBackgroundColor);