Non
Non

Reputation: 8589

How to set jquery event on named function with a keyboard event in it?

I have these 3 functions:

var triggerWynPopup = function(e) {
    ...
    e.preventDefault();
};

var closeWynPopup = function(e) {
    ...
    e.preventDefault();
};

var closeWynPopupKeyb = function(e) {
    if (e.keyCode === 27) {
        closeWynPopup();
    }
    e.preventDefault();
};

And I am calling them like this:

$btClose.on('click', closeWynPopup);
$wynPop.on('click', triggerWynPopup);
$document.on('keyup', closeWynPopupKeyb);

It works cool when I do click to call closeWynPopup and triggerWynPopup, but when I call $document.on('keyup', closeWynPopupKeyb); it throws an error

Uncaught TypeError: Cannot read property 'preventDefault' of undefined


What could be the error?

Upvotes: 0

Views: 97

Answers (3)

no special event definition is required for the function. you can do it this way.

var closeWynPopupKeyb = function() {
    if (event.keyCode === 27) {
        closeWynPopup(event.keyCode);
    }
    event.preventDefault();
};

var closeWynPopup = function(x) {
    console.log(x);
};

document.addEventListener("keydown", closeWynPopupKeyb);

Upvotes: 2

yajiv
yajiv

Reputation: 2941

if (e.keyCode === 27) {
    closeWynPopup(e);  //  here pass 'e'
}

As you are passing nothing in closeWynPopup(); so e will undefine in function definition so it is giving an error.

if (e.keyCode === 27) {
    closeWynPopup();  // passing undefined(in function e become 'undefined')
}

Upvotes: 2

Rahul Desai
Rahul Desai

Reputation: 15501

You missed passing e to closeWynPopup() in closeWynPopupKeyb

var closeWynPopupKeyb = function(e) {
    if (e.keyCode === 27) {
        closeWynPopup(e); // pass "e" here
    }
    e.preventDefault();
};

Upvotes: 3

Related Questions