JS - How to remove an event listener with function that accepts multiple arguments?

298 Views Asked by At

I am having issues removing a listener in my JS. I have a div that when you hover over it it triggers function cardHoverGrow with html inline style "onmouseover= cardHoverGrow(this.id)". The cardHoverGrow function triggers as expected and passes the id. The parts of the function where I change the css properties of the element work as expected so I left it out.

//this function receives div id 'elemID', works fine.
function cardHoverGrow (elemID) {
  let hoverTopTemp='';
  let hoverLeftTemp='';
//{other code that changes width,height etc. of the element}//
  document.getElementById(elemID).addEventListener('mouseleave',mouseLeaveListener(elemID,hoverTopTemp,hoverLeftTemp));
}

The 'mouseleave' listener successfully creates and it succesfully triggers 'mouseLeaveListener' when the mouse leaves the element. The 'removeEventListener' inside this function is working. However, elsewhere in the code I have a function that I want to remove the listener created by cardHoverGrow (when user clicks on the element). 'dragElement' triggers fine except it doesn't remove the listener from the element.

I have checked that its the same element being targeted. I tried removing 'theLeaveListener' but then I get an error 'undefined', because it's in the other function. I wrote the listener function like I did because I needed to pass the arguments without calling the function each time 'cardHoverGrow' was called.

I want that after the 'cardHoverGrow' triggers if a user presses down on the element (not click) and triggers 'dragElement' the listener created in 'cardHoverGrow' is removed. Anyone know how I can do this?

//this function receives div id 'elemID', works fine.
function cardHoverGrow (elemID) {
  let hoverTopTemp='';
  let hoverLeftTemp='';
//{other code that changes width,height etc. of the element}//
  document.getElementById(elemID).addEventListener('mouseleave',mouseLeaveListener(elemID,hoverTopTemp,hoverLeftTemp));
}

//This successfully triggers when mouse leaves the element.
function mouseLeaveListener (elemID,hoverTopTemp,hoverLeftTemp) {
  return function theLeaveListener() {
    cardHoverShrink(elemID,hoverTopTemp,hoverLeftTemp);
    //this remove listener is working.
    document.getElementById(elemID).removeEventListener('mouseleave', theLeaveListener);
  }
}

//Somewhere else in the code I trigger 'dragElement' and 'cardHoverShrink' (succesfully) and I want to also remove the listener created at the same time.

function dragElement (globelmnt){
  //{code for adjusting CSS properties of globelmnt (element derived from document.getElementbyID). Works fine
cardHoverShrink(globelmnt.id,topadjust,leftadjust);
document.getElementById(globelmnt.id).removeEventListener('mouseleave', mouseLeaveListener());

}

0

There are 0 best solutions below