Search code examples
jqueryiframeyoutubeembedkeypress

applying jquery on escape key event while playing you tube video in iframe


I am embedding a you tube video in a div and ahow it on click of a button. Now I want to hide the div on escape keypress event.

Html

<div 
class="divpop" 
id='<iframe width="640" height="480" src="https://www.youtube.com/embed/5uGo0L4ribY" frameborder="0" allowfullscreen></iframe>'><img class="project-img project-img-visible" src="images/videos/img1.jpg" alt=""'>
</div>

Jquery

$(".divpop").click(function(){
       $("#popup_video").html((this).id);
      });
$(#popup_video).keypress(function(e){
     if (e.which==0){
       $("#popup_video").empty();
     } });

Solution

  • That is an extremely unorthodox means of doing what you are trying to achieve.

    I'd like to recommend that you put the dynamic variables of the youtube video in expando properties.

    Html

    <div class="divpop" youtube_width="640" youtube_height="480" youtube_vid="5uGo0L4ribY">
        <img class="project-img project-img-visible" src="images/videos/img1.jpg" alt="">
    </div>
    

    As for hiding the video, you need to target the document, and keycode '27' for Escape

    Jquery

    $(".divpop").click(function(){
        // Create new iframe entity:
        var $yt_embed = $('<iframe/>'); //dollar before variable indicates jquery object
        // Instantiate and assign attributes
        var yt_url = "https://www.youtube.com/embed/"+$(this).attr('youtube_vid');
        $yt_embed.attr( 'src', yt_url )
                 .attr( 'width', $(this).attr('youtube_width') )
                 .attr( 'height', $(this).attr('youtube_height') );
        $("#popup_video").html($yt_embed);
    });
    
    
    $(document).keyup(function(e) {
        if (e.keyCode == 27) { $('#popup_video').empty(); }   // esc
    });
    

    Here's the fiddle: http://jsfiddle.net/yAvBh/2/