When attempting to center the image, an error is displayed in the browser stating "cannot read property width of null." I have tried dividing the screen width by 2 but I am unable to understand why this error is occurring.
var mobile = document.getElementById("mobile");
var monitor = document.getElementById("monitor");
var tab = document.getElementById("tab");
var header = document.getElementById("header");
var position = (screen.width - monitor.width)/2;
monitor.style.left = position+"px;";
function initScroll(){
if(window.pageYOffset >500){
mobile.style.left = "300px";
tab.style.right = "250px";
header.style.height = "60px";
header.style.fontSize = "25px";
}else{
header.style.height = "60px";
header.style.fontSize = "25px";
mobile.style.left = "0px";
tab.style.right = "0px";
}
}
window.addEventListener("scroll",initScroll);
*{padding: 0;margin: 0;font-family:arial;}
#header{height:100px;background-color: #354458;font-size: 40px;color:#fff; text-align:center;line-height:2.5;
position:fixed; width:100%;z-index:20;
-moz-transition: 2s height, 2s font-size;
-o-transition: 2s height, 2s font-size;
-webkit-transition: 2s height, 2s font-size;
transition: 2s height, 2s font-size;
}
#banner{background: #3a9ad9;height:400px;position:fixed;width:100%;
top:100px;font-size:50px; text-align: center; color
:#fff;z-index:10;
}
#banner > * {
margin-top:30px;
}
#content{
top:500px;
position:relative;
height:1000px;
padding-top:200px;
background-color: #fff;
z-index:15;
}
#mobile{
position: absolute;
left: 0;
z-index: 15;
top: 470px;
-moz-transition: 2s left;
-o-transition: 2s left;
-webkit-transition: 2s left;
transition: 2s left;
}
#monitar{position: relative;}
#tab{
position: absolute;
right: 0;
z-index: 15;
top: 385px;
-moz-transition: 2s right;
-o-transition: 2s right;
-webkit-transition: 2s right;
transition: 2s right;
}
<html>
<head>
<title>Java script Scroller</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="./css/style.css"/>
<script src="./js/custom.js"></script>
</head>
<body>
<div id="wrapper">
<div id="header">Header</div>
<div id="banner">
<h1>My Animation</h1>
<h2>First collapsable header</h2>
<h3>Apurva Kinkar</h3>
</div>
<div id="content">
<img id="mobile" src="./img/1.jpg" />
<img id="monitar" src="./img/2.png" />
<img id="tab" src="./img/3.jpg" />
</div>
</div>
</body>
</html>