I believe I’m having a relatively simple problem with a video player implementation in javascript. To start, I want to add a string to an array and reference that first string entry as the src of my source in my video tag. I then want the video to begin playing once the src is received.
I have not implemented the code for the latter since I haven’t gotten past the former yet. I’ve seen people make reference to a .load() function call after changing the src but I don’t know if I’m correctly setting the src to begin with.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Untitled Document</title> <style> video { background-color:#333; } </style> </head> <body> <script type="text/javascript"> var width = (1280 * 0.1); var height = (720 * 0.1); var resized = false; function getWidth(){ return width; } function getHeight(){ return height; } //Create array. Checkbox adds video to list. //"Submit" button gives first video in list to player. var videoList = new Array(); var i = 0; //incrementer //Use checkbox's value as argument function addVideo(value){ videoList[i] = value; i++; } function videoSubmit(){ document.getElementById("player").setAttribute("src", videoList[i]); } </script> <video id="test" width="getWidth()" height="getHeight()"> <source id="player" src="null" type="video/avi" width="getWidth()" height="getHeight()"/> </video> <br/> <form id="selector" action=""> <input type="checkbox" name="firstvideo" value="test.avi" onClick="addVideo(test.avi)"/> sample 1.avi<br/> </form> <button onClick="videoSubmit()"> Submit</button> </body> </html>
I’m quite new to javascript and am still trying to wrap my head around it. Any helpful information is greatly appreciated.
Answer
Looks like i
has the wrong value. Try:
function videoSubmit(){ document.getElementById("player").setAttribute("src", videoList[ i - 1 ]); }
There are a few other issues as well. Here’s a fixed version – enjoy:
Another problem:
You can’t do this:
<video id="test" width="getWidth()" height="getHeight()">
If you want to programatically set those attributes, you must do it the same way you are with the src attribute. Sometimes you’ll see this sort of construct, but it’s clumsy:
<script>document.write('<video id="test" width="' + getWidth() + '" ...')</script>
Unrelated to the Q – you could skip a lot of javascript learning pain by jumping straight to jquery. It does incur a page-load penalty, but it cures a lot of the annoyances of pure javascript. Doing it the old fashioned way will give you “valuable experience” – which those of us who have it value probably more than warranted.