event.keyCode or event.ctrlKey not working in Internet Explorer 8

I want to capture the Ctrl+click event, the event.keyCode and all other stuff for detecting control clicks work fine on Chrome and Firefox. On IE am getting the following error:

>>alert(event.keyCode);
"Object required"

I tried detecting Shift+click, Alt+click everything is fine. I tried handling the exception but nothing works. I even tried detecting the type of the return type for the keyCode getting number for Alt + click and Shift + click. Ctrl+click am not able to capture anything out of it.

My code, which uses jQuery 1.10.2, is below:

$(document).keydown(function (event) {
    if (event.which == "17") cntrlIsPressed = true;
});
$(document).keyup(function () {
    cntrlIsPressed = false;
});
var cntrlIsPressed = false;

function call_new_url(param1) {
    if (cntrlIsPressed) {
        window.open("http://www.google.com");
    }
}

Can some one help me out on this?

Upvotes: 0

Views: 4405

Answers (1)

user2428118
user2428118

Reputation: 8104

Instead of listening for a keyPress event, you can check for event.ctrlKey and event.shiftKey in your click listener.

JavaScript:

$('#myLink').click(function (event) {
    if (event.ctrlKey) {
        console.info('Ctrl is pressed');
    } else {
        console.warn('Ctrl isn\'t pressed');
    }

    if (event.shiftKey) {
        console.info('Shift is pressed');
    } else {
        console.warn('Shift isn\'t pressed');
    }
});

See this code in action at JSFiddle or edit it.

Upvotes: 1

Related Questions