Preventing default behavior in Key Listeners in YUI

I have a webpage where I would like to redirect Ctrl + N to another behavior. I followed the YUI example of the Key Listeners registrar, and my function is called, but Firefox still creates a new browser window. On IE7, everything works fine. How to stop displaying a new window?

Example:

var kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:function(event) { YAHOO.util.Event.stopEvent(event); // Doesn't help alert('Click');}}); kl2.enable(); 

You can remove the default behavior. Google Docs override Ctrl + S to save the document, rather than open the Firefox save dialog. I tried the example above with Ctrl + S, but the Firefox save dialog still pops up. Since Google can stop the save dialog, I'm sure there is a way to prevent most default keyboard shortcuts.

+4
source share
4 answers

The trick is the fn function.

Experimentally, you can see that the type of the function for fn takes two parameters. The first pair contains the TYPE of the event. The second contains ... and this is not serious: an array containing the code point at index 0 and the actual event object at index 1.

So, changing your code a bit, it should look like this:

 function callback(type, args) { var event = args[1]; // the actual event object alert('Click'); // like stopEvent, but the event still propogates to other YUI handlers YAHOO.util.Event.preventDefault(event); } var kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:callback}); kl2.enable(); 

Also, for lisp love, do not use raw code points in your code. Use โ€œN'.charCodeAt (0) instead ofโ€œ 78. โ€Or wrap it as a function

 function ord(char) { return char.charCodeAt(0); } 
+7
source

I just guess, but I donโ€™t think it can be done.

If possible, it definitely shouldn't be. Common keyboard shortcuts are something you should not mess with. What's next? Click the close window button to open a new window ...

0
source

Using the YUI event utility, you can try using the stopEvent method:

However, since most users are used for those keystrokes that do a specific thing in the browser (a new window in your example), I always avoid collisions, which in fact means that I do not use any of the meta or control keys.

I just use letters on my own, and thatโ€™s fine as long as you donโ€™t have any text fields, so this tip may be less useful to you.

0
source

Although overriding the default browser shortcuts by default is not trivial, it is worth doing in some cases because it gives a more professional look to the application. Take a look at this script:

http://www.openjs.com/scripts/events/keyboard_shortcuts/index.php#disable_in_input

It turns out that everything is fine for me.

0
source

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


All Articles