How to fire event in jquery when pressing alt + tab or windows + d button?

I want to fire an event when the alt + tab or windows + d key is pressed. Following is my warning code when the mouse pointer is away from the browser window. But even if the user presses alt + tab or Windows + D, this event should also occur. Can someone help me in this regard please? Folowing is my code for your reference:

<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script> var timer; $(document).ready(function () { $(document).mouseleave(function () { //alert("Mouse is away"); customAlert("your mouse is away"); }); }); function customAlert(customText) { $("#popUp").html(customText); timer = setInterval(customAlert2, 5000); $("#popUp").dialog({ dialogClass: "no-close", buttons: [{ text: "OK", click: function () { $(this).dialog("close"); clearInterval(timer); } }] }); } function customAlert2() { location.reload(); $("#popUp2").dialog({ dialogClass: "no-close", buttons: [{ text: "OK", click: function () { $(this).dialog("close"); } }] }); } </script> </head> <body> <h1>My first Javascript program</h1> <p>Hello World!</p> <div id="popUp" title="First alert message"></div> <div id="popUp2" title="Second alert message">Time is over</div> </body> </html> 
+2
source share
2 answers

jwerty is a great plugin that allows you to create functions for certain key combinations.

eg:.

 jwerty.key('ctrl+shift+P', function () { [...] }); 
+2
source

note , if you want to process any keys that they registered with the OS (for example: Alt + Tab ), you CANNOT do this with jQuery.

you need to assign your event to unregistered keys to trigger your event using jQuery.

you can try some kind of code, like a hit, to handle what you need.

 var keys = {}; $(document).keydown(function (e) { keys[e.which] = true; }); $(document).keyup(function (e) { delete keys[e.which]; }); if( (keys[91] && keys[68]) || (keys[18] && keys[9]) ) /*windows+d OR alt+tab*/ { /* your code */} 


or

use jwerty lib to do this. code example:

 jwerty.key('ctrl+shift+P', function () { // your code }); 

and support:

 jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { // your code }); 


and there is a simple javaScript Mousetrap library for handling keyboard shortcuts. Take a look at an example:
 Mousetrap.bind('h', function() { // your code }); 

OR

It also supports combinations:

 Mousetrap.bind(['ctrl+h', 'ctrl+l'], function(e) { // your code } 

Hope this will be helpful for you.

+2
source

Source: https://habr.com/ru/post/973347/


All Articles