I was given two functions that are nearly identical, but one uses a parameter.
function handleBlur() {
const list = event.currentTarget.closest("#nav ul");
if (!event.relatedTarget || !list.contains(event.relatedTarget)) {
closeNav();
}
}
function handleDropdownBlur(btn) {
const list = event.currentTarget.closest("#nav ul");
if (!event.relatedTarget || !list.contains(event.relatedTarget)) {
closeDropdown(btn);
}
}
I was able to change the first function to work properly by simply adding event
as the function parameter.
function handleBlur(event) {
const list = event.currentTarget.closest("#nav ul");
if (!event.relatedTarget || !list.contains(event.relatedTarget)) {
closeNav();
}
}
How would I change the second function to not warn of deprecation?
I tried adding event
as both a first and second parameter, but this breaks the functionality.
The function is called later in the code like this:
dropdowns.forEach((dropdown) => {
const list = dropdown.querySelectorAll("li a");
list[list.length - 1].addEventListener("blur", (event) => {
handleDropdownBlur(dropdown.previousElementSibling);
});
});
2
Answers
Forwarding the event by changing the function to
function handleDropdownBlur(event, btn)
and then calling the function usinghandleDropdownBlur(event, dropdown.previousElementSibling)
fixed the deprecation warning and it works fine.Your current function definition of
handleDropdownBlur
uses the globalevent
variable, which is indeed deprecated.Changing your code to:
Will forward the
event
object provided byaddEventListener
tohandleDropdownBlur
as the first argument. You then have to change thehandleDropdownBlur
definition to also accept this argument:This doesn’t have to be the first argument and could also be forward as the second, or any other argument for that matter. But it’s common practice to let
event
always be the first argument with any additional data following it.