Bato Dor
Bato Dor

Reputation: 841

append iframe by clicking youtube screenshot of it

I have a long list of videos and there are a lot of iframes that slows all of the browsers. I decided to use their screenshots only. By clicking on the screenshot, the iframe will be shown and screeshot will be hidden. I just set the iframe to be hidden by default, but I want the iframes to be appended dynamically so that iframes would not be written in HTML code at all, here is my code:

<div class="youtube">
                <div class="description">Desciption 1</div>
                <div class="youtube_thumb">
                    <img src="http://img.youtube.com/vi/mqf6K6qYOWg/0.jpg" style="width:325px;border:0;" />
                    <iframe width="325" height="250" src="http://www.youtube.com/embed/mqf6K6qYOWg" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>
            <div class="youtube">
                <div class="description">Desciption 2</div>
                <div class="youtube_thumb">
                    <img src="http://img.youtube.com/vi/GIc14HyiLNs/0.jpg" style="width:325px;border:0;" />
                    <iframe width="325" height="250" src="http://www.youtube.com/embed/GIc14HyiLNs" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>

and so on..

and javascript:

$('.youtube_thumb > img').click(function(){
            var $img = $(this);
            $img.hide();
            $img.next().show();
        });

and style:

.youtube_thumb iframe { display:none; }
.youtube_thumb:hover { cursor:pointer; }

As you can see and probably know, the screenshot I get is directly from youtube, thus the screenshot link: mqf6K6qYOWg/0.jpg and in frame link: /embed/mqf6K6qYOWg are the same, I think it is possible by using the link of the screenshot, to append the iframe with the same link. How i can do this?

Upvotes: 1

Views: 895

Answers (2)

epascarello
epascarello

Reputation: 207521

$('.youtube_thumb > img').click(function(){
    var parts = this.src.split("/");  //grab the url and split it into parts
    var id = parts[parts.length-2]; //grab the second to last piece
    $('<iframe width="325" height="250" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe>').insertAfter(this);  //append the iframe
    $(this).hide();  // .remove();
});

Upvotes: 2

David Fregoli
David Fregoli

Reputation: 3407

wrap the img into an a tag with

<a class="wrap" href="http://www.youtube.com/embed/mqf6K6qYOWg"><img /></a>

jquery

$('.wrap').on('click', function() {
    var src = $(this).attr('href');
    $(this).before('<iframe width="325" height="250" src="'+src+'" frameborder="0" allowfullscreen></iframe>');
    $(this).remove();
    return false;
)}

Upvotes: 1

Related Questions