With this little snippet, you can close an iframe modal with the escape key.

I use Fancybox on projects from time to time. It’s a good standalone solution when you need a popup window, and it even has support for iframes. It’s that last part that I want to address here.

Fancybox has built-in support for closing modals by hitting the escape key. Unfortunately, this doesn’t work when an iframe modal has the focus. This makes sense, of course; the iframe page knows nothing about the Fancybox script or the fact that it’s being included in a modal.

So the solution is easy: you have to make the page aware. Keeping in mind that this requires you to have control over the page being included in an iframe — and I expect this will be the case anyway — this little script will allow you to call the parent page and close the Fancybox modal.


As for triggering the code on the escape key, that can be found in this StackOverflow post . (You want to do this on the keyup event, not keydown or keypress, so it only fires once, and at the end of the press.

$(document).keyup(function(e) {
     if (e.keyCode == 27) { // escape key maps to keycode `27`
        // DO YOUR WORK HERE

There’s one more thing, though. If that iframe page were opened by itself, you don’t want any code firing when the escape key is pressed. Chances are that the Fancybox script isn’t going to be loaded, which will result in a js error. So we need to add one more thing to our iframe page’s escape keypress event listener, a simple check to make sure the page is loaded inside an iframe:

!(window === window.parent)

So, all together now:

$(document).keyup(function(e) {
     if (!(window === window.parent) && e.keyCode == 27) {

Here is a demonstration button. Click it, you know you want to.

Open iframe