Generate an iframe from the youtube link with jquery

Asked

Viewed 393 times

-1

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

3 answers

0

var linkYoutube = //link do YouTube.
var $iframe = $('<iframe/'>).attr('src', linkYoutube);
$('ID_DIV').append($iframe);
  • did not work, it generates the iframe, but without the video

  • I adjusted my answer.

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>');

0

Suppose we want to show the following video from Youtube, within a iframe:

https://www.youtube.com/watch?v=[id_do_video]

For this we must convert him to:

https://www.youtube.com/embed/[id_do_video]

And then pass that url to the 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.