I have a quick question. I am trying to incorporate an onload event in HTML5. Here is my code but it refuses to work. Please let me know what I am doing wrong.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Animation</title>
<script>
document.getElementById('videoBackground').onload = function()
{
document.body.style.backgroundColor = 'black';
}
</script>
<script type="text/javascript" src="js/animCD.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<video id="videoBackground" poster="img/loading.png" onload="function()" width="1920" height="1080" preload="auto" onprogress="animCD_onprogress();" onended="animCD_start();">
<source id="colorVid_mp4" type="video/mp4" src="img/luther_color.mp4">
</video>
Specifying someElement.onload = function() { }
is how you create an onload handler in a general sense. The reason your doesn't work is that your script block comes before the element in question and runs immediately, at which point document.getElementById()
can't find that element because it hasn't been parsed yet.
You can fix this by moving the script block to somewhere after the element (many people put their scripts at the end of the body), or by calling it in an onload handler for the page:
window.onload = function() {
document.getElementById('videoBackground').onload = function() {
document.body.style.backgroundColor = 'black';
}
};
Although the page/window's onload should be called after all content is loaded, so I'm not sure that there's any point creating more onload handlers from there.
I notice you also have an onload="function()"
attribute in your html. That is another way to specify a handler, although inline event attributes are not the preferred way to do things, but you'd need to put an actual function name onload="someFunction()"
to call a named function defined elsewhere, or put the code directly:
<video ... onload="document.body.style.backgroundColor='black';" ...>
At the point where you are executing getElementById('videoBackground')
the element with the id videoBackground
doesn't exist yet.
Either move the script below where you created the videoBackground
element or run the script after the DOM loads using document.onload
.