Generate an iframe from the youtube link with jquery

0

I would like to generate a iframe from youtube that will return to a div so the user paste the video link into a field, I know how to create with php, but I would like to do with jquery, so I already return to the div without needing ajax .

    
asked by anonymous 08.11.2017 / 13:24

3 answers

0
var linkYoutube = //link do YouTube.
var $iframe = $('<iframe/'>).attr('src', linkYoutube);
$('ID_DIV').append($iframe);
    
08.11.2017 / 13:28
0

I found the answer:

function getId(url) {
        var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
        var match = url.match(regExp);

        if (match && match[2].length == 11) {
            return match[2];
        } else {
            return 'error';
        }
    }

    var myId = getId('link_do_video');

    $('#myId').html(myId);

    $('#myCode').html('<iframe width="560" height="315" src="//www.youtube.com/embed/' + myId + '" frameborder="0" allowfullscreen></iframe>');
    
08.11.2017 / 13:46
0

Suppose we want to show the following YouTube video within a iframe :

  

link

For this we must convert it to:

  

link

Then pass this url to src of iframe :

function goYoutube() {
  var link = document.getElementById('link');
  var iframe = document.getElementById('youtube');
  
  // Busca o "ID" do vídeo
  var id = link.value.split('watch?v=')[1];

  // Verifica se obteve um "ID"
  if(!id) {
    alert("Link está incorreto!");
    return;
  }
  
  // Seta o src do iframe para a url convertida
  iframe.src = "https://www.youtube.com/embed/" + id;
}
<label for="link">Digite o link aqui</label>
<input type="text" id="link" onblur="goYoutube()">

<br>
<br>

<iframe id="youtube" width="560" height="315" frameborder="0" allowfullscreen></iframe>
    
08.11.2017 / 13:59