Closing modal with e.keypress

1.1k views Asked by At

I have the following modal box:

<div class="modal-video" id="v-5417">
<div class="video-player">
                <video id="v-5417-tape" preload="none">
                    <source type="video/mp4" src="videos/anthem-od47.mp4">
                    <source type="video/webm" src="videos/anthem-od47.webm">
                </video>
                <div class="close-modal fade-control"></div>
</div>
</div>

and trying to use the following e.keyCode to close the modal:

        $(document).keydown(function (e) {
            if (e.keyCode == 27) {
                $(".modal-video").hide();
            }
        });

This is only hiding the video, but not closing the modal and killing the video. How can I completely close the modal and video together?

2

There are 2 answers

0
Marian Gibala On

jQuery .hide() just changes the CSS style to display:none, so your video is hided and still playing in the background. To fix that issue, you can stop playing the video by standard HTML5 pause() method.

If hiding $(".modal-video") doesn't work for you, then I assume you need to hide it's parent - but we have to see more your code to be sure about that.

$(document).keydown(function (e) {

    if (e.keyCode == 27) {

        var video = document.getElementById("v-5417-tape");
        video.pause()

        $(".modal-video").parent().hide();


    }
});

If you are using some kind of player template or plugin, and click on class "close-modal" hides the modal as you expect - then you can use jQuery .toggle() method to call click event on that element, when you press your key.

$(document).keydown(function (e) {

    if (e.keyCode == 27) {

        var video = document.getElementById("v-5417-tape");
        video.pause()

        $(".close-modal").toggle("click")


    }
});
0
Matt On

The active state has to be removed, and that disabled the popup.

$(document).keydown(function (e) {
        var video = document.getElementById("v-5417-tape");
        if (e.keyCode == 27) { 
        if(video.play){
            video.pause();
        }
            $(".modal-video").removeClass("active");

        }
    });