Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  9] [ 3]  / answers: 1 / hits: 17869  / 10 Years ago, mon, november 3, 2014, 12:00:00

I am trying to change a YouTube video iframe source with jQuery, but looks like running into cross origin issue. My jquery code:



var videourl = $(.videourl).html();
$(.actualyoutube iframe).attr('src',videourl);


iframe gets new src value, but no video is displayed. Any ideas?



extended explanation:



There is a popup div with embeded youtube video



<div class=youtubepopup>
<div class=closeyoutube>X</div>
<div class=actualyoutube>
<iframe width=420 height=315 src= frameborder=0 allowfullscreen></iframe>
</div>
</div>


There is a certain td which contains a new src url. There is no other place or way to get this url except from this td.



<td class=videourl>//youtube.com/whatevervideo</td>


And there is a script that should add src on open popup and remove on closing.



var videourl = $(.videourl).html();
$(.youtubecap).click(function() {
$(.actualyoutube iframe).attr('src', videourl);
$(.youtubepopup).fadeIn('slow');
});
$(.closeyoutube).click(function() {
$(.youtubepopup).fadeOut('slow');
$(.actualyoutube iframe).removeAttr('src');
});
$(.youtubepopup).click(function() {
$(.youtubepopup).fadeOut('slow');
});


p.s. now that i laid it out, user3385530 is probably right


More From » jquery

 Answers
6

You cannot show pages from www.youtube.com inside an iframe. The correct way is to use their video embed codes inside your web page. IFrame embeds are easier, the URL you need to display in an iframe looks like this:



http://www.youtube.com/embed/VIDEO_ID_GOES_HERE


Just place an iframe such as this inside your web page:



<div class=actualyoutube>
<iframe width=560 height=315 src=http://www.youtube.com/embed/VIDEO_ID_GOES_HERE frameborder=0 allowfullscreen></iframe>
</div>


Finally, assuming you are able to extract video id from the URLs using jQuery, you can use this to display videos*:



var videoid = S2ISrpNM-0s;
$(.actualyoutube iframe).remove();
$('<iframe width=420 height=315 frameborder=0 allowfullscreen></iframe>')
.attr(src, http://www.youtube.com/embed/ + videoid)
.appendTo(.actualyoutube);


* Changing the src property of an iframe that is already displaying a YouTube video did not work; I therefore suggest destroy-iframe-recreate-iframe approach.


[#68925] Friday, October 31, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyreem

Total Points: 540
Total Questions: 94
Total Answers: 90

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;