Bind this context and also pass event object

I am getting the error ReferenceError: event is not defined for the following code:
document.addEventListener('keydown', EscapekeyCloseDropdown.bind(button, event));

The function looks like this:

function EscapekeyCloseDropdown (event) {
	if (event.key === 'Escape') {
		closeDropdown.call(this);
	}	else {
		return;
	}
}

you don’t need to bind the event object. it will be passed to the function by the event system.

Specifically, event.target is the element that received the event.

I am having a similar problem again. The following code works in Chrome and Safari but is showing a error in the console in Firefox - ReferenceError: event is not defined:

var dropdownItems = document.querySelectorAll('[data-dropdown-item]');
dropdownItems.forEach((item, index) => {
	item.addEventListener('keydown', handleUpArrow.bind(null, index));
	item.addEventListener('keydown', handleDownArrow.bind(null, index));
})

function handleUpArrow (index) {
	if (event.key === "ArrowUp") {
		if (index === 0) {
			dropdownItems[dropdownItems.length - 1].focus();
		}
		else {
			dropdownItems[index - 1].focus();
		}
	}
}

function handleDownArrow (index) {
	if (event.key === "ArrowDown") {
		if (index === dropdownItems.length - 1) {
			dropdownItems[0].focus();
		}
		else {
			dropdownItems[index + 1].focus();
		}
	}
}

Okay, perhaps @Dormilich’s advise was a little lightly worded.

DONT bind. Just… apply the EventListener as standard. In fact, simplify your code, bind a single keydown event that handles both ArrowUp and ArrowDown.

You still have to list the event parameter; the arguments the function gets called with will be appended to the arguments you previously bound to the function:

function handleErrorUp (index, event) {/* ... */}

In some browsers the event object will indeed be available regardless, but that’s by no means standard behaviour and you shouldn’t rely on that.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.