4

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

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

My incomplete JQuery is as such;

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

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

Any help welcome. Thanks

1
  • You have a syntax error, attr on "you-tube"-element Commented Oct 8, 2014 at 13:32

2 Answers 2

5

HTML : (just ID gonna 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/


More better (using data attr)

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/

Sign up to request clarification or add additional context in comments.

Comments

0

I figured out how to autoplay the videos (below). Any idea how to add an anchor to each link? So... on a long list of YT links, you click a link near the bottom of the page, anchor to the iframe at the top of the page, and autoplay the video? Here's the autoplay bit (+'?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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.