Sean
Sean

Reputation: 29790

Can I intercept control-A keypresses on IE?

I'm trying to use jQuery to intercept control-A keypresses on my web page, like so:

$(document).keypress(function (event) {
    if (event.ctrlKey && (event.which == 65 || event.which == 97)) {
        event.preventDefault();
        // ...
    }
});

This works on Firefox, but on IE7, my event handler doesn't get called, and all of the text on the page gets selected instead (as happens on Firefox without the event handler).

Is there any way I can intercept control-A's on IE?

Upvotes: 0

Views: 1830

Answers (2)

Matt
Matt

Reputation: 1242

If you do a return false in the event handler then it will cancel the browsers behavior. Depending on the browser it can behave differently (for instance keypress will still fire on firefox after a keydown has canceled it, while IE will stop it).

Upvotes: 0

Waleed Amjad
Waleed Amjad

Reputation: 6808

This works under FF 3.5 and IE7 for me:

    $(function() {
        var isCtrl = false; 

        $(document).keyup(function (e) { 
            if(e.keyCode == 17)
                isCtrl = false;
        }).keydown(function (e) { 
            if(e.keyCode == 17)
                isCtrl = true;

            if(e.keyCode == 65 && isCtrl == true) {
                alert('Intercepted CTRL+A');
                e.preventDefault();
            }
        }); 
    });

Upvotes: 6

Related Questions