...

View Full Version : Resolved Video Switcher ElementById "null or not an object"?



Charlie8776
01-04-2012, 03:09 PM
Below are the full Javascript and HTML to detect a browser and either display HTML5 or Flash video. However, the script is returning an error, 'document.getElementById(...)' is null or not an object. Any suggestions?


var deviceAgent = navigator.userAgent.toLowerCase();
$brwzr = deviceAgent.match(/(chrome|firefox|safari|msie 9.0)/);


if ($brwzr) {
document.getElementById("video_5").setAttribute("class", "on");
}
else {
document.getElementById("video_F").setAttribute("class", "on");
}


<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Video Switch</title>
<script language="JavaScript" src="index/js/detect.js"></script>

<style>
<!--
.off {
display: none;
}

.on {
display: inline;
}
-->
</style>

</head>
<body>

<div id="video_5" class="off">HTML5!</div>
<div id="video_F" class="off">Flash!</div>

</body>
</html>

Amphiluke
01-04-2012, 03:21 PM
Are you sure the page is completely loaded when you try to find an element by its id?
You have to call the getElementById method only from within the event handler like window.onload or DOMContentLoaded.

Charlie8776
01-04-2012, 03:29 PM
Are you sure the page is completely loaded when you try to find an element by its id?
You have to call the getElementById method only from within the event handler like window.onload or DOMContentLoaded.

Ah, okay. I added
<body onload="switch()"> to the HTML and put the script in the function "switch". It works, many thanks!

Amphiluke
01-04-2012, 03:35 PM
You are welcome. But it would be better to use the window.onload event handler, according to the principles of "unobtrusive JavaScript".


window.onload = function() {
var deviceAgent = navigator.userAgent.toLowerCase();
$brwzr = deviceAgent.match(/(chrome|firefox|safari|msie 9.0)/);
if ($brwzr) {
document.getElementById("video_5").setAttribute("class", "on");
} else {
document.getElementById("video_F").setAttribute("class", "on");
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum