Reputation: 8280
So i have a function which assigns a mouseover, this adds a hover tooltip div and a mouseout event to the div that triggers it so i can remove the tooltip.
The problem is the mouseout event fires but keeps firing when ever i move the mouse anywhere outside of the div, so it fires many hundreads of times for every pixel movement of the mouse.
This is the set up:
function ToolTip(data)
{
var div = createDiv();
div.className = 'ToolTip';
div.innerHTML = 'This is a tooltip!';
addChild(div,document.body); // appends to given element
this.addEventListener('mouseout',function(){removeToolTip(div);},false);
}
function removeToolTip(el)
{
console.log('test');
this.removeEventListener('mouseout',removeToolTip,false);
removeDiv(el); //removes perfectly fine
}
for(var i=0;i<data.length;i++)
{
var div = document.getElementById('id'+i);
(function(i){
div.addEventListener("mouseover",function(){ToolTip(data[i]);},false);
})(i);
}
I do not understand why mouseout keeps firing, i get test
in my console log so it should be removing the event listener. Where have i gone wrong?
Upvotes: 0
Views: 1754
Reputation: 707326
Your event handling logic is pretty confused.
First off, you're adding a mouseover event handler to each of a series of divs.
Then, each time that mouseover event is triggered (which can be many times), you are calling ToolTip()
which adds a mouseout event on this
which appears to be the window
object because ToolTip()
is just a plain function call so this
will either be the global object or undefined
(in strict mode).
Then, in removeToolTip()
, you are trying to call removeEventListener('mouseout', ...)
, but that won't work because you're passing a different function to it than the addEventListener()
used. removeEventListener()
requires that you pass in the exact same function that you passed to addEventListener()
or it won't do anything. So, since you're passing a different function, nothing is removed and you get a build-up of mouseout events and all on the window object.
Structurally, you need to fix:
Make sure you're installing the event handler on the correct object. this
in your functions is NOT what you want it to be. I would suggest you stop using this
in those functions and pass in the object you want to operate on as an argument to those functions.
Pass in an actual named function (not an anonymous function) to addEventListener()
so you can later use it with removeEventListener()
.
When you call removeEventListener()
you must pass the exact same named function reference that you used with addEventListener()
.
Make sure you're trying to call removeEventListener()
on the right object also.
For more info on how this
is set in a function call, see the five numbered points in this prior answer.
Upvotes: 1