Prevent Default Behavior in Key Listeners in YUI


I have a web page where I'd like to remap Ctrl+N to a different behavior. I followed YUI's example of register Key Listeners and my function is called but Firefox still creates a new browser window. Things seem to work fine on IE7. How do I stop the new window from showing up?


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

It is possible to remove default behavior. Google Docs overrides Ctrl+S to save your document instead of bringing up Firefox's save dialog. I tried the example above with Ctrl+S but Firefox's save dialog still pops up. Since Google can stop the save dialog from coming up I'm sure there's a way to prevent most default keyboard shortcuts.

By : Cristian


The trick is the 'fn' function is whack.

Experimentally, you can see that the function type for fn takes two parameters. The first param actually contains the TYPE of event. The second one contains... and this is screwy: an array containing the codepoint at index 0 and the actual event object at index 1.

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

function callback(type, args)
    var event = args[1]; // the actual event object

    // like stopEvent, but the event still propogates to other YUI handlers
var kl2 = new YAHOO.util.KeyListener(document, { ctrl:true, keys:78 }, {fn:callback});

Also, for the love of lisp, don't use raw code points in your code. Use 'N'.charCodeAt(0) instead of "78". Or wrap it up as a function

function ord(char)
    return char.charCodeAt(0);
By : Tac-Tics

Using YUI's event util, you could try and use the stopEvent method:

However, because most users are used to those keypresses doing a particular thing in the browser (new window in your example), I always avoid clashes, which in effect means I don't use any of the meta or control keys.

I simply use letters, on their own, which is fine until you have text entry boxes, so this bit of advice might be less useful to you.

This video can help you solving your question :)
By: admin