Recently I’ve had a nasty issue regarding an autocomplete component that refused to render its options properly.
When you hovered on the component, it flickered like NYE fireworks in Times Square 🎆
Turns out the problem was created by using
onmouseover on a parent element of the autocomplete component.
When I changed it to
onmouseenter, the problem was solved!
…and this was odd enough to make me wonder about mouse events in js.
Of course, I’m not talking about your everyday
onclick. That’s cool, everyone knows to just put some event handler there and go on.
Nope, I’m talking about these four, highly similiar events, that when used without care can cause a lot of unnecessary renders1.
The fantastic four (© Marvel) are:
|Occurs when the pointer is moved onto an element
|When you care about entering the whole element, not for entering children
|Occurs when the pointer is moved out of an element
|When you care about exiting the whole element, not for exiting children
|Occurs when the pointer is moved onto an element, or onto one of its children
|When you care about entering the element, and also for entering children
|Occurs when a user moves the mouse pointer out of an element, or out of one of its children
|When you care about exiting the element, and also for exiting children
Note the slight difference between these two sets of events - while
onmouseleave occur on the element,
onmouseover occur on the element
🚨or one of its children.🚨
This means that
onmouseleave do not bubble up - they do not propagate up the document hierarchy,
hence they’re used when you care about the element as a whole.
This codesandbox should make things more graphic:
Note how many times that box of
onmouseover changes! In React, this would cost us in multiple renderings, that we might not need.
Happy new year everyone, and always remember - “a
mouseevent a day keeps the render count at bay” 🌈
I use React, so I natively talk about renderings. But this also applies to vanilla js. ↩