3

I created a lightbox using the following script:

<script type="text/javascript">
    $(document).ready(function(){
            $(".BtnAction").click(function(){                               
                var objPopup = $($(this).attr("rel"));

                var mask = $("<div/>", {
                    id : "mask",
                    style: "background:#000; display:block;top:0;left:0;position:absolute;opacity:0.8;filter: alpha(opacity=80);width:100%;height:100%;z-index:9998;",
                    click: function(){
                        $(objPopup).hide();
                        $(this).remove();   
                    }       
                }); 

                $(".PopupWrap").before(mask);
                objPopup.show();
            });

            $(".CloseIcon").click(function(){
                $(this).parent().hide();
                $("#mask").remove();
            });

    });
</script>

How can I implement the ESC key so that when it is clicked, the lightbox will close as well?

Thanks so much.

Ori
  • 259
  • 2
  • 8
  • 27

1 Answers1

12

You can add an esc key listener to the document within your $(document).ready() block, and repeat the code you currently have for the $('.CloseIcon').click() function, but target the lightbox by it's Id:

$(document).ready(function(){

// Your existing code

    $(document).keyup(function(e) { 
        if (e.keyCode == 27) { // esc keycode
            $('#lightboxId').hide();
            $('#mask').remove();
        }
    });
});

https://stackoverflow.com/a/3369624/1010337

Community
  • 1
  • 1
ActiveDan
  • 349
  • 2
  • 6
  • Wow, thank you so much! That definitely helped. Since I have several light boxes that are targeted by different selectors, I changed the code to be: //escape functionality $(document).keyup(function(e) { if (e.keyCode == 27) { // esc keycode $("#popup1, #popup2, #popup3, #popup4, #popup5").hide(); $('#mask').remove(); } }); – Ori Jun 13 '12 at 16:13
  • Glad it helped, one last thing; rather than targetting each lightbox by it's unique Id, maybe add a class to them all that you can target them by with, e.g. $('.js-lightbox'). That way if you ever add/remove some you won't need to change the script. – ActiveDan Jun 13 '12 at 23:35