Load a specific iframe using jQuery onClick function

I am trying to load a specific iframe (Youtube video) depending on what I clicked.

<a href="#" class="video"></a>
<a href="#" class="video"></a>
<div class="video-wrapper">
    <iframe src="" id="youtube"></iframe>
</div>

My unfinished jQuery as such,

<script>
  $(document).ready(function(){
  $('a.video').click(function() {
   var videoSelect = $(this).attr('href');

  $("#youtube-video").attr
  });
});
</script>

Any help is appreciated. Thanks

+4
source share
2 answers

HTML: (just ID will be easier)

<a href="JDglMK9sgIQ" class="video">#1</a>
<a href="LpKyzSxVhk4" class="video">#2</a>

<div class="video-wrapper">
    <iframe id="youtube" width="560" height="315" frameborder="0" allowfullscreen></iframe>
</div>

jQuery:

$('a.video').click(function () {
    var id = $(this).attr('href');
    var src = '//www.youtube.com/embed/'+id;
    $("#youtube").attr('src', src);
    return false;
});

Demo: http://jsfiddle.net/tdLnoxmo/


Better (using attr data)

HTML:

<a href="#" class="video" data-youtube="JDglMK9sgIQ">#1</a>
<a href="#" class="video" data-youtube="LpKyzSxVhk4">#2</a>

<div class="video-wrapper"></div>

jQuery:

$('[data-youtube]').click(function () {
    var id = $(this).attr('data-youtube');
    var src = '//www.youtube.com/embed/'+id;
    var iframe = '<iframe id="youtube" width="560" height="315" frameborder="0" src="'+src+'" allowfullscreen></iframe>';
    $(".video-wrapper").html(iframe);
    return false;
});

Demo: http://jsfiddle.net/l2aelba/tdLnoxmo/75/

+5
source

, (). , ? ... YT , iframe ? (+ '? Autoplay = 1'):

$(window).load(function(){
$('a.video').click(function () {
    var id = $(this).attr('href');
    var src = '//www.youtube.com/embed/'+id+'?autoplay=1';
    $("#youtube").attr('src', src);
    return false;
0

All Articles