1. We have to know the trigger event after stop typing
How to trigger an event in input text after I stop typing/writing?
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('input').keyup(function() {
delay(function(){
// Here check if video exists
// if video exist show it
}, 1000 );
});
answered by https://stackoverflow.com/users/2269004/ata-ul-mustafa :
2. We have to know if a youtube video exists
How do I check if a video exists on YouTube, in client side
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc',function(data,status,xhr){
alert(data.data.title);
}).error(function() { alert("error"); });
answered by https://stackoverflow.com/users/3748701/innomanik
3. If video exists show it (in the iframe):
<iframe id="myIframe" width="300" height="200"></iframe>
Set the content of the src attribute of the iframe dynamically with jQuery:
var url = "https://www.youtube.com/embed/" + videoID;
$('#myIframe').attr('src', url)
UPDATE (v3)
Therefore you need an api key. How to get it you can read here. And read this about security.
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#youtubeId').keyup(function() {
delay(function() {
var videoID = $('#youtubeId').val();
var videos = "https://www.googleapis.com/youtube/v3/videos";
var apiKey = "AIzaSyAzYHm1iwMocB9pW2uZrz_6Sqte5t_bXGo"; // Insert here your api key
var fieldsTitle = "fields=items(snippet(title))";
var fieldsEmpty = "";
var part = "part=snippet";
function getUrl(fields) {
var url = videos + "?" + "key=" + apiKey + "&" + "id=" + videoID + "&" + fields + "&" + part;
return url;
}
$.get(getUrl(fieldsEmpty), function(response) {
var status = response.pageInfo.totalResults;
var title;
if (status) {
$.get(getUrl(fieldsTitle), function(response) {
title = response.items[0].snippet.title;
$('#info').text(title);
var url = "https://www.youtube.com/embed/" + videoID;
$('#myIframe').attr('src', url)
})
} else {
title = "Video doesn't exist";
$('#info').text(title);
$('#myIframe').attr('src', "");
}
});
}, 1000);
});
Demo: https://embed.plnkr.co/ixAFtU/