MitulP91
MitulP91

Reputation: 1335

Obtain Event Object in Function With Parameters

So I'm adding a keydown listener on my page when you are focused on a certain element, but I want to remove it when you are not on this element. This works fine, but I can't find a way to pass the event object (needed for e.preventDefault()) into this function. The following is a relevant snippet of my code:

// Named function for keydown listener (I need to pass the line 
// and layer objects into the function)
function keydownListener(line, layer) {
    e.preventDefault();
    // ... using the line and layer for various things ...
}

// adds event listener when you click on specific element
some_element.addEventListener('click', function() {(
    window.addEventListener('keydown', keydownListener(line, layer));
});

// removes event listener when you click on anywhere else (not real code. just to 
// demonstrate the idea)
anything_else.addEventListener('click', function() {
    window.removeEventListener('keydown', keydownListener);
});

Is there no way to pass the event object into a function with other parameters?

Upvotes: 0

Views: 41

Answers (2)

Robin Drexler
Robin Drexler

Reputation: 4457

You could try to pass the event to the keydownListener when click event is triggered

function handler(e)
    keydownListener(line, layer, e)
};

// adds event listener when you click on specific element
some_element.addEventListener('click', function() {
    window.addEventListener('keydown', handler)
});


// Named function for keydown listener (I need to pass the line 
// and layer objects into the function)
function keydownListener(line, layer, e) {
    e.preventDefault();
    // ... using the line and layer for various things ...
}

Upvotes: 1

Greg Burghardt
Greg Burghardt

Reputation: 18888

The event listener function receives the event as its first argument, though some browsers have this as a global variable:

foo.addEventListener("click", function(event) {
    event = event || window.event;
    callOtherFunction(event, arg1, arg2);
});

Upvotes: 1

Related Questions