javascript - inserting text from a div to an api call for embed
i have the following basic script to make an api call to vimeo and insert the embed to a div #embed. I'm having trouble however getting it to grab the text of another div #embedthis and assembling the api call from that.
The code below does work if placed in the <body>
. However I want to set this up properly as I would like to also b开发者_开发百科e able to change the content of #embedthis dynamically, updating the displayed embed. Any help is so much appreciated!
script:
// URL to get embed
var videoUrl = document.getElementById('embedthis').innerHTML;
// oEmbed endpoint for Vimeo using JSON
var endpoint = 'http://www.vimeo.com/api/oembed.json';
// Tell Vimeo what function to call
var callback = 'embedVideo';
// Put together the URL
var url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&callback=' + callback + '&width=640';
// put video on page
function embedVideo(video) {
document.getElementById('embed').innerHTML = unescape(video.html);
}
// load data from Vimeo
function MakeEmbed() {
var js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', url);
document.getElementsByTagName('head').item(0).appendChild(js);
};
window.onload = MakeEmbed;
view:
<div id="embed">
...
</div>
<div id="embedthis">http://vimeo.com/24453255</div>
With this I get document.getElementById('embedthis')" is null
, probably because #embedthis isn't loaded yet.
The issue is that when var videoUrl = document.getElementById('embedthis').text()
is called, the <div>
has yet to be created by the browser, since this code is called as soon as the browser encounters it, which I assume is in your <head>
section.
Your code should work if you move it to a function which is called on window.onload
or document.ready
as this guarantees that the element has been created.
Edit
Like so (comments removed for brevity):
var url;
function embedVideo(video) { ... }
var my_onload = function() {
var videoUrl = document.getElementById('embedthis').innerHTML;
var endpoint = 'http://www.vimeo.com/api/oembed.json';
var callback = 'embedVideo';
url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&callback=' + callback + '&width=640';
MakeEmbed();
}
window.onload = my_onload;
精彩评论