Issue
I'm beginning to teach myself javascript. I thought I would try to make a script that embeds a youtube video when provided with a URL. Can anyone help me understand what I'm doing wrong when I create the iframe element, set the attributes, and append it as a child to the div? I'm using JSFiddle, and when I inspect the element no tag appears to have been added to the div. Thanks!
Edit: Here's my jsfiddle link: http://jsfiddle.net/86W8N/2/
<p>Click the button to call function</p>
YoutubeURL: <input id="url" type="text">
<button onclick="myFunction()">Try it</button>
<div id="video_div">
</div>
<script>
function myFunction() {
var urlValue = document.getElementById("url").value;
var videoID = urlValue.substring(urlValue.indexOf('=') + 1);
var video = document.createElement("iframe");
video.setAttribute(title, "Test");
video.setAttribute(width, "440");
video.setAttribute(height, "390");
video.setAttribute(src, "http://www.youtube.com/embed/" + videoID);
video.setAttribute(frameborder, "0");
var div_element = document.getElementById("video_div");
div_element.appendChild(video);
}
</script>
Solution
Your code will stop executing, throwing a title is not defined
exception at
video.setAttribute(title, "Test");
In setAttribute(title, ...)
you're using title
as though it was a variable named title, but that doesn't exist. You want instead to pass the string value "title"
:
video.setAttribute('title', 'Test');
... and the same for the other attributes...
A few more hints since you're using JSFiddle:
- Make a habit of saving the fiddle and always provide the link together with your question
- Under "Framework & Extensions" in the left-hand panel, make sure you've set the javascript to load with "no wrap", otherwise you won't be able to call the method from your html the way you've done. (This applies when you're defining your JavaScript functions in the JavaScript panel. I see from your updated question with included fiddle link that you're currently putting it all in the HTML markup, so you won't have this issue)
- Hit F12 in your browser, and you will be able to see the actual error message that your code produces.
Answered By - David Hedlund
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.