How can I replace the youtube link and make it work? - javascript

I have tried to make a youtube interface to play music, but I want to change the music so I've made this script. The problem is, when I change the link the video won't work anymore and it gives me an error.
<iframe id="iframe" width="500" height="315" src="https://www.youtube.com/embed/SHFTHDncw0g" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>
</iframe>
<input type="text" name="link" id="link" size="40">
<input type="button" value="Play" onclick="changeLink();">
<script>
function changeLink() {
var changeLink = document.getElementById("link").value;
document.getElementById("iframe").src += changeLink;
}
</script>

You are adding a new link instead of replacing, because you used += instead of = in your Javascript. As a result, you have 2 links concatenated.
Try replacing:
document.getElementById("iframe").src += changeLink;
With this:
document.getElementById("iframe").src = changeLink;

Related

How to select an iframe and pass its src to a function

I have a javascript file that displays a variable number of videos embedded from youtube and displayed in a grid.
I need the users to be able to select one video and click submit where I will will store the src link of that video in a variable.
Below is the related javascript portion:
playListItems.forEach(item => {
const videoId = item.snippet.resourceId.videoId;
output += `
<div class="col s3">
<iframe width="100%" id="videoFrame" height="auto"
src="https://www.youtube.com/embed/${videoId}?rel=0" frameborder="0" encrypted-media" >
</iframe></div>
`;
}
HTML:
<form id="form1">
<div class="input-field">
<input type="submit" id="but1" value="Save Selection">
</div>
</form>
How do I do that using an event handler or any other possible solution?
why not use const videoId as the id of each iframe? Because you can't use an id more then once. Then in an onclick handler of each iframe element you can fire a function that sets the value of <input type="submit" id="but1" value="Save Selection"> to this.id.
Like so:
playListItems.forEach(item => {
const videoId = item.snippet.resourceId.videoId;
output += '<div class="col s3">
<iframe width="100%" id="${videoId}" height="auto"
src="https://www.youtube.com/embed/${videoId}?rel=0" frameborder="0" encrypted-media" onclick='submitVid(this.id);'>
</iframe></div>';
}
Then the submitVid(video) function will look something like this:
function submitVid(video) {
//the video variable will hold this.id or the videoId
//Here you can do whatever you want with video.
//Full video id:
var url = "https://www.youtube.com/embed/" + video + "?rel=0";
//pass value to a textfield to submit
document.getElementById("textfield").value = video;
}
A better is to just store the videoId and not the full url. It saves space and it is faster.
Hope this helps! If not, please comment
try some_var = document.getElementById("videoFrame").src

How to play youtube video using angularjs

All the following code is work successfully to get youtube playlist and display it with no problem. But I can't play any video from this list using angular js.
Angular JS
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope, $http) {
//contentDetails - snippet
$http.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLlMsyZB0poTDYImmOliKyiC-jpAFUsr6X&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw')
.then(function (response) {
$scope.records = response.data.items;
});
$scope.PlayFun = function (Val) {
var Vid_ID = Val;
var New_Vid = "<iframe width='450' height='283' src='https://www.youtube.com/embed/" + Vid_ID + "?autoplay=1&loop=1&rel=0&wmode=transparent' frameborder='0' allowfullscreen wmode='Opaque'></iframe>";
var Vid_Elm = document.getElementById("video");
Vid_Elm.setAttribute("crs", New_Vid);
};
});
HTML
<iframe id="video" style="position:fixed;top:150px;right:50px;" width="420" height="315" src="//www.youtube.com/embed/9B7te184ZpQ?rel=0" frameborder="0" allowfullscreen></iframe>
<br />
<ul data-ng-app="myApp" data-ng-controller="myCtrl">
<li data-ng-repeat="x in records">
<img class="img-thumbnail" style="width:100px; height:80px;"
src="{{x.snippet.thumbnails.default.url}}" />
<br />
<input data-ng-click="PlayFun(x.snippet.resourceId.videoId)" type="button" value="{{x.snippet.title}}" />
</li>
</ul>
My problem specifically is in "$scope.PlayFun" where I can't run a video from the list by video id using angular js.
My approach is to change iframe html on ng-click to pass new selected Vid_ID and to make it "autoplay=1" put it doesn't work.
You can set the src of the iframe to ng-src like so:
<iframe id="video" style="position:fixed;top:150px;right:50px;" width="420" height="315" ng-src="{{videoSource}}" frameborder="0" allowfullscreen></iframe>
And in your controller you simply change the url of video source and it will automatically change the video source. You do need to trust as resource url though for security (which means injected $sce as well)
$scope.videoSource = $sce.trustAsResourceUrl("//www.youtube.com/embed/9B7te184ZpQ?rel=0");
Working PLunker demo

Change YouTube iframe src with jQuery

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
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.
<div class="service-video-media">
<iframe id="main-play" width="560" height="315" src="https://www.youtube.com/embed/uTcj2v85y34" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<div class="video-list">
<img src="https://img.youtube.com/vi/uTcj2v85y34/1.jpg" video-id="uTcj2v85y34" />
<img src="https://img.youtube.com/vi/jRuR4GaSsBI/1.jpg" video-id="jRuR4GaSsBI" />
<img src="https://img.youtube.com/vi/ec7aQPLSBsU/1.jpg" video-id="ec7aQPLSBsU" />
<img src="https://img.youtube.com/vi/uTcj2v85y34/1.jpg" video-id="uTcj2v85y34" />
<img src="https://img.youtube.com/vi/jRuR4GaSsBI/1.jpg" video-id="jRuR4GaSsBI" />
<img src="https://img.youtube.com/vi/ec7aQPLSBsU/1.jpg" video-id="ec7aQPLSBsU" />
</div>
</div>
<script>
jQuery(document).ready(function(){
jQuery('.video-list img').on('click',function () {
var videoId = jQuery(this).attr('video-id');
var videoUrl = 'https://www.youtube.com/embed/'+videoId;
jQuery('#main-play').attr('src',videoUrl);
});
});
</script>
This will not work because page is parsed and only on refresh with new ulr will happen.
You need to use ajax to pre-load the page with new url and then to set iframe.

Update the href of a Iframe link in html

So here's my situation.
I have a page HTML that displays a YouTube video, using a standard iFrame link. What I am trying to do is have a text box on my page where people would enter a video's ID and the video would reload with the new link or video ID entered.
Code HTML:
<p> Type your video's ID here: <input type="text" name="VideoID"></p>
<iframe title="YouTube video player" src="http://www.youtube.com/embed/hqiNL4Hn04A" width="480" height="390" frameborder="0"></iframe></p>
You need to request the video ID within a form like
<p>
<form id="getytid">
<label>Type your video's ID here:</label>
<input type="text" name="VideoID" />
<input type="submit" value="go" />
</form>
</p>
<p>
<iframe id="theFrame" title="YouTube video player" src="" width="480" height="390" frameborder="0"></iframe>
</p>
Notice we assigned an ID to the form and the iframe so we can manipulate them through jQuery.
Then you could use this code to update the iframe with a new video ID :
jQuery(document).ready(function($) {
$("#getytid").on("submit", function (e) {
e.preventDefault();
$("#theFrame").attr("src", "http://www.youtube.com/embed/" + $("input[name=VideoID]").val()+"?autoplay=1")
}); // on
}); // ready
See JSFIDDLE
NOTE:
The initial iframe html doesn't have any src attribute set. You can leave it empty until the visitor inputs an ID or you can fill it with a default video path
you should look at this post as I think this is what you want.
dynamically set iframe src
http://jsfiddle.net/MALuP/
<script type="text/javascript">
function iframeDidLoad() {
alert('Done');
}
function newSite() {
var sites = ['http://getprismatic.com',
'http://gizmodo.com/',
'http://lifehacker.com/']
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
Save the youtube url as a variable.
Html:
<input type="text" name="VideoID" id="youtubevid" />
JS:
var youtube = "http://www.youtube.com/embed/"; // base
var video;
var url;
// set value
$('#youtubevid').on('change', function() {
video = $('#youtubevid').val();
url = youtube + video;
// set link attribute here in iframe.
//$('#idofiframehere').attr('src', url);
});

displaying a youtube video using object tag in a html page

I have the following code where I am trying to embed a youtube player into a html page.
I do not see any errors on the console, but the player is not added on the html page.
<form name="urlReaderForm" onSubmit=" return validateForm()" method="post">
Url: <input type="text" name="url"><br>
edit: Times: < input type="Number" name="times"<br>
<input type="submit" type="submit" value="Submit">
</form>
<div id="youPlayer"></div>
<script>
function validateForm() {
var url=document.forms["urlReaderForm"]["url"].value;
var loopCounter=document.forms["urlReaderForm"]["times"].value;
var len = url.length;
var vIDpos=url.indexOf("v=");
var vID=url.substring(vIDpos+2,len-1);
alert(''+vID);
var html_var='';
html_var ="<object style='height: 390px; width: 640px'> <param name='movie' value='https://www.youtube.com/v/'"+vID+"'?version=3&feature=player_embedded&loop='"+loopCounter+"'&playlist='"+vID+"'><param name='allowFullScreen' value='true'><param name='allowScriptAccess' value='always'><embed src='https://www.youtube.com/v/'"+vID+"'?version=3&feature=player_embedded&loop='"+loopCounter+"'&playlist='"+vID+"' type='application/x-shockwave-flash' allowfullscreen='true' allowScriptAccess='always' width='425' height='344'></object>​";
document.getElementById("youPlayer").innerHTML = html_var;
}
</script>
there's a couple of issues in the sample above...
there is no field for
var loopCounter=document.forms["urlReaderForm"]["times"].value; to read on the form
when you extract the URL from the form you strip off the last character. Use var vID=url.substring(vIDpos+2,len);
unless you add return false;
to the end of the script it will reload the page because of the so you'll never see your errors
I would recommend using the more modern iframe embeddeding, but if you still need to stick with your solution then try the following:
function validateForm()
{
var url=document.forms["urlReaderForm"]["url"].value;
//var loopCounter=document.forms["urlReaderForm"]["times"].value;
loopCounter = 0;
var len = url.length;
var vIDpos=url.indexOf("v=");
var vID=url.substring(vIDpos+2,len);
alert(''+vID);
var html_var='';
html_var ="<object style='height: 390px; width: 640px'><param name='movie' value='https://www.youtube.com/v/"+vID+"?version=3&feature=player_embedded&loop='"+loopCounter+"'&playlist='"+vID+"'><param name='allowFullScreen' value='true'><param name='allowScriptAccess' value='always'><embed src='https://www.youtube.com/v/"+vID+"?version=3&feature=player_embedded&loop='"+loopCounter+"'&playlist='"+vID+"' type='application/x-shockwave-flash' allowfullscreen='true' allowScriptAccess='always' width='425' height='344'></object>";
console.log(html_var);
document.getElementById("youPlayer").innerHTML = html_var;
return false;
}
I have to agree with previous poster about the build-in embeded code. To give you two new ideas I did this myself on two occassion using one and the other on the 2nd site.
<iframe width="640" height="360" src="http://www.youtube.com/embed/9m-L5InQZvM?feature=player_detailpage" frameborder="0" allowfullscreen></iframe>
Is for the embeded one, the 2nd option I used was that I just made a list with videos and a general iframe just to have a target like so
<body class="center">
<h2 class="media">Videos</h2>
<ul id="list" class="videolist">
<li class="videolist"></li>
<li class="videolist"></li>
</ul>
<iframe id="video-frame" src="" width ="600" height ="350" name="video-frame">
</iframe>
</body>
And then put the embeded code into separate .html files like so
<!DOCTYPE html>
<iframe width="576" height="324" src="http://www.youtube.com/embed/FjCehYrEbO0?feature=player_detailpage">
Your browser does not support frames, please update your browser
</iframe>
But the main point is still, use a iframe and it's still considered HTML5 valid even though frames can be frowned upon, but that is general use. You can still use frames but they should be used to serve a greater purpose and not just because it's "easier" to divide/update content on a page.

Categories

Resources