Onclick element simulate Esc key

5.7k Views Asked by At

I have the following situation:

When the user clicks on a link, through Javascript Esc key should be triggered. So to be able to explain it better I have the following code so far:

1.I've created a function:

//my function
function invokeEscKey() {
    var ev = document.createEvent('KeyboardEvent');
    ev.initKeyEvent(
        'keydown', true, true, window, false, false, false, false, 27, 0);
    document.body.dispatchEvent(ev);
}

also tried this with jQuery:

//my function
function invokeEscKey() {
    jQuery.event.trigger({
        type : 'keypress', 
        which : 27 
    });
}

2.And when the user clicks on the href, the function should be called:

$(function() {
    $('a.close').click(function() {
        //call this function to simulate ESC key press
        invokeEscKey();
    });
});

But this doesn't work at all. My question is, what is the best way to solve this?

Note: The reason I ask this is because I have a popup with the F11 key (full screen mode) is activated. When the user clicks on the close button, the F11 must be undone, which is normally done by pressing on the ESC key. And I want this to be done automatically.

1

There are 1 best solutions below

0
On

JavaScript can't trigger OS-level events from the browser window, except the cases when it is natively supported by the browser via special functions or APIs. You can't send a system-level keyboard event with ESC key to close fullscreen mode, or, say, launch system help with F1.

Instead you may use Fullscreen API which is supported by major browsers:

if (document.exitFullscreen) {
    document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
}

MORE: http://www.paulund.co.uk/javascript-full-screen-api