user193661 user193661 - 3 months ago 9
Javascript Question

Cannot read property style error

I'm using nginx and chrome as the browser. I'm just trying to change the background color of a div. And the isolated JS works in a fiddle. But the complete markup doesn't work.

I keep getting "TypeError: Cannot read property 'style' of null" in the browser console for the banner div.

<!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8"> -->
<title>ZZZ lin!</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<!-- <link rel="stylesheet" href="/static/global.css" type="text/css"> -->
<style type="text/css">
#banner {
display:inline;
position:absolute;
top:0px;
left:0px;
height:40px;
width:100%;
background-color:green;
}
</style>
<script type="text/javascript">
var banner_colors = ['#d99b00', '#7f5b00', '#332d0d', '#fffb00', '#888c69', '#9bbf30', '#dbf2b6', '#1f5900', '#59b376', '#00e667', '#004d2d', '#80ffec', '#739993', '#00cbe6', '#263233', '#0095f2', '#1d5273', '#b6dbf2', '#3354cc', '#162559', '#8f93bf', '#2a00e6', '#474359', '#390080', '#5b3973', '#250033', '#b539e6', '#c499cc', '#800071', '#660031', '#d93685', '#8c4668', '#cc002c', '#d9a3ae', '#660009', '#ff808a', '#403031'];
var i = 0, howManyTimes = banner_colors.length;
function f() {
document.getElementById('banner').style.backgroundColor = banner_colors[i];
i++;
if( i < howManyTimes ){
setTimeout( f, 1000 );
}
}
document.onload = f();

</script>
</head>
<body>
<div id="banner">
</div>
<div id="main-content">
<p>Main page content goes here</p>
<p>Main page content goes here</p>
<p>Main page content goes here</p>
<p>Main page content goes here</p>
<p>Main page content goes here</p>
</div>
<h1>Hello from Flask!</h1>
</body>
</html>

Answer

Use window.addEventListener("load", f) to run it once the page loads (where f is the contents of your <script> tag wrapped inside a function).