Reputation: 121
I am trying to play youtube video in a html page with a custom play button like this fiddle.
HTML
<button id="btn">Play</button>
<object type="application/x-shockwave-flash" id="yt" data="http://www.youtube.com/v/6eK-W32IME0?fs=1&enablejsapi=1&hl=en_US" width="330" height="200"><param name="allowScriptAccess" value="always"/></object>
JavaScript
var yt = document.getElementById("yt");
document.getElementById('btn').onclick = play;
function play() {
yt.playVideo();
}
The code works fine in JSFiddle, but when I put same thing in a text file and execute, the video is not playing. Please suggest me in this regard, Thanks in advance.
Upvotes: 0
Views: 180
Reputation: 926
In the code, you are trying to access element via document.getElementById
, which depends on where you write the <script>
tag. Fiddle's script loading process or location may be different from normal browsers. As per your code, if the <script>
tag is before <button>
, then it will not work, where as if you put <script>
after <object>
, then it will work.
I modified your code as below which i was able to run successfully.
<html>
<head>
<script type="text/javascript">
function init() {
var yt = document.getElementById("yt");
document.getElementById('btn').onclick = play;
}
function play() {
yt.playVideo();
}
</script>
</head>
<body onload="init()">
<button id="btn">Play</button>
<object type="application/x-shockwave-flash" id="yt"
data="http://www.youtube.com/v/6eK-W32IME0?fs=1&enablejsapi=1&hl=en_US"
width="330" height="200">
<param name="allowScriptAccess" value="always"/>
</object>
</body>
</html>
Page has to be loaded via http protocol because of SOP reasons, browser will not allow access to player if loaded as file protocol
Upvotes: 1