So after reading a recently answered question i am unclear if i really understand the difference between the mouseenter()
and mouseover()
. The post
Old question, but still no good up-to-date answer with insight imo.
These days, all browsers support mouseover/mouseout
and mouseenter/mouseleave
. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave
, but silently puts them on a wrappers around mouseover/mouseout
as the following code shows and makes its own slightly different interpretation of mouseenter/mouseleave
.
The exact behavior of events is especially relevant on “delegate handlers”. Unfortunately, jQuery also has its own different interpretation of what delegate handlers are and what they should receive for events. That fact is shown in another answer for the simpler click event.
So how to properly answer a question about jQuery, which uses Javascript wording for events and handlers, but makes both different and does not even mention that in its documentation?
First the differences in “real” Javascript:
enter/over
gets a corresponding leave/out
(possibly late/jumpy)mouseenter/mouseleave
mouseover/mouseout
After some testing, it shows that as long as you don’t use jQuery “delegate handlers with selector registration”, the emulation is unnecessary but reasonable: It filters out mouseover/mouseout
events that a mouseenter/mouseleave
would not get. The target is messed, though. The real mouseenter/mouseleave
would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout
carried.
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);
function log(tag, event) {
const li = list.insertBefore(document.createElement('li'), list.firstChild);
// only jQuery handlers have originalEvent
const e = event.originalEvent || event;
li.append(`${tag} got ${e.type} on ${e.target.id}`);
}
outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
div {
margin: 20px;
border: solid black 2px;
}
#inner {
min-height: 80px;
}