mouseenter vs mouseover: change background in JavaScript
Intermediate · 4 min read
Move your mouse over a card on a shopping site and it often lights up. That is a hover effect: something changes while the pointer is over an element and changes back when it leaves. JavaScript has two pairs of events for this, and they look so alike that people swap them without noticing. Until the effect starts flickering.
In this tutorial you will change a box's background color when the mouse enters it, clear it when the mouse leaves, and then count exactly when each event fires, so you can see why mouseenter and mouseover are different. You should have used addEventListener before.
The four mouse events
There are two pairs:
mouseenterfires when the pointer arrives on an element.mouseleavefires when it goes.mouseoveralso fires when the pointer arrives.mouseoutfires when it goes.
The difference is about children, the elements nested inside. Our box has a bold word inside it:
<div id="box">hover me, and my <b>bold child</b></div>
Bubbling in one paragraph
When an event happens on an element, it doesn't stop there. It travels up through the element's parent, then that parent's parent, all the way to the top of the page. This is called bubbling. A listener on the box hears events that started on the bold child, because they bubble up through the box.
mouseover bubbles. mouseenter does not. That one fact is the whole exercise.
Here is the exercise. Try it yourself first, or read on and we will build it.
3 Change the background on mouse enter
fairChange an element's background colour when the mouse enters it. Then find out why mouseenter and mouseover are not interchangeable.
Stuck? Three hints, smallest first
- 1.
mouseoverbubbles.mouseenterdoes not. - 2. So
mouseoverfires again every time the pointer crosses onto a child element. - 3. Pair whichever you choose with its opposite:
mouseleavefor enter,mouseoutfor over.
Step 1: color on enter, clear on leave
const box = document.getElementById('box');
box.addEventListener('mouseenter', () => { box.style.backgroundColor = '#eaf6ef'; });
box.addEventListener('mouseleave', () => { box.style.backgroundColor = ''; });
box.dispatchEvent(new Event('mouseenter'));
console.log(box.style.backgroundColor !== ''); // true: a color is set
box.dispatchEvent(new Event('mouseleave'));
console.log(box.style.backgroundColor === ''); // true: cleared
style.backgroundColor is the CSS background-color property, written in camelCase. Setting it to an empty string '' removes the color you set, so the box goes back to how the stylesheet made it.
The two dispatchEvent lines pretend the pointer arrived and left. In a browser you would just move the mouse.
Notice the pair: mouseenter goes with mouseleave. Mixing pairs (for example mouseenter with mouseout) gives you an "on" event and an "off" event that follow different rules.
Step 2: count both events
Now listen for mouseenter and mouseover on the same box and count how often each fires.
const box = document.getElementById('box');
const child = box.querySelector('b');
let enters = 0;
let overs = 0;
box.addEventListener('mouseenter', () => enters++);
box.addEventListener('mouseover', () => overs++);
// the pointer arrives on the box...
box.dispatchEvent(new Event('mouseenter'));
box.dispatchEvent(new Event('mouseover', { bubbles: true }));
// ...then moves onto the bold child, twice
child.dispatchEvent(new Event('mouseover', { bubbles: true }));
child.dispatchEvent(new Event('mouseover', { bubbles: true }));
console.log(enters, overs); // 1 3
When the pointer moves onto the bold word, the browser fires mouseover on the bold word. It bubbles up, so the box's listener runs again. The pointer never left the box, yet mouseover counted three times. mouseenter stayed at one, because it doesn't bubble: it only fires for the element itself.
This is why mouseover is the wrong choice for a hover effect on a box with anything inside it. Your code would run again every time the pointer crossed a child, and with mouseout as its partner, the color can flicker off and on as you move around.
Step 3: target and currentTarget
When an event bubbles, two properties tell you where you are:
const box = document.getElementById('box');
const child = box.querySelector('b');
box.addEventListener('mouseover', (event) => {
console.log(event.target.tagName, event.currentTarget.tagName); // B DIV
});
child.dispatchEvent(new Event('mouseover', { bubbles: true }));
event.target is where the event started: the bold child. event.currentTarget is the element whose listener is running right now: the box. During bubbling they differ. Later exercises, like event delegation, are built on exactly this.
Step 4: you may not need JavaScript at all
For a plain color change, CSS can do it on its own with the :hover pseudo-class:
#box:hover {
background: #eaf6ef;
}
It needs no listeners, and it can't get stuck. Use JavaScript when hovering has to do more than change a style, such as loading a preview or counting views.
The full solution
The full solution colors the box on mouseenter, clears it on mouseleave, and counts both events while the pointer crosses onto the bold child. Its checks confirm the box starts uncolored, entering colors it, leaving clears it, crossing onto the child fires mouseover but not mouseenter, and target and currentTarget differ during bubbling. Press Run to see the counts, then try the live demo and watch the mouseover count climb.
allow-scripts only, so it cannot reach this page.const child = el('b', {}, 'bold child');
const box = el('div', { id: 'box' }, ['hover me, and my ', child]);
document.body.appendChild(box);
let enters = 0;
let overs = 0;
// mouseenter does NOT bubble, so it fires once for the box itself.
box.addEventListener('mouseenter', () => { enters++; box.style.backgroundColor = '#eaf6ef'; });
box.addEventListener('mouseleave', () => { box.style.backgroundColor = ''; });
// mouseover DOES bubble, so crossing onto a child fires it again.
box.addEventListener('mouseover', () => { overs++; });
// Entering the box itself: mouseenter does not bubble, so bubbles is false.
const enterBox = () => box.dispatchEvent(new Event('mouseenter', { bubbles: false }));
const overBox = () => fire(box, 'mouseover');
const overChild = () => fire(child, 'mouseover'); // bubbles up to the box
console.log('background at rest:', JSON.stringify(box.style.backgroundColor));
enterBox();
overBox();
console.log('after entering :', box.style.backgroundColor, '| enters', enters, 'overs', overs);
// Now the pointer moves onto the bold child, without leaving the box.
overChild();
overChild();
console.log('after crossing onto the child twice: enters', enters, 'overs', overs);
console.log('<- mouseover counted the child crossings; mouseenter did not');
box.dispatchEvent(new Event('mouseleave', { bubbles: false }));
console.log('after leaving :', JSON.stringify(box.style.backgroundColor));
Output
12 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('nothing is coloured at rest', box.style.backgroundColor, '');
test('entering colours it', (() => { enterBox(); return box.style.backgroundColor; })(), '#eaf6ef');
test('leaving clears it', (() => { box.dispatchEvent(new Event('mouseleave', { bubbles: false })); return box.style.backgroundColor; })(), '');
test('mouseenter fired twice in total, once per real entry', enters, 2);
test('mouseover fired more often', overs > enters, true);
test('crossing onto a child fires mouseover again', (() => { const before = overs; overChild(); return overs - before; })(), 1);
test('but not mouseenter', (() => { const before = enters; overChild(); return enters - before; })(), 0);
test('because mouseover bubbles', (() => { const e = new Event('mouseover', { bubbles: true }); return e.bubbles; })(), true);
test('and mouseenter does not', (() => { const e = new Event('mouseenter', { bubbles: false }); return e.bubbles; })(), false);
test('a child crossing reaches the box as the currentTarget', (() => { let seen = null; const fn = (ev) => { seen = ev.currentTarget === box && ev.target === child; }; box.addEventListener('mouseover', fn); overChild(); box.removeEventListener('mouseover', fn); return seen; })(), true);
test('so target and currentTarget differ during bubbling', true, true);
test('the colour survives a child crossing', (() => { enterBox(); overChild(); return box.style.backgroundColor; })(), '#eaf6ef');
mouseenter fires once when the pointer arrives and does not bubble. mouseover bubbles, so it fires again every time the pointer crosses onto a nested element — the assertions count the difference. For a hover effect on a box containing anything at all, mouseenter/mouseleave is what you want; mouseover will re-trigger constantly as the pointer moves over the contents.
The pattern behind that is worth keeping: during bubbling, event.target is where the event started and event.currentTarget is the element whose listener is running. The last assertions check they differ, which is the mechanism the delegation exercise later depends on.
Also note that a plain hover colour needs no JavaScript. #box:hover { background: #eaf6ef } is more robust, cannot get stuck, and costs nothing.
Common mistakes
- Using
mouseoverfor a hover effect. It fires again every time the pointer crosses a child. Usemouseenterandmouseleave. - Mixing the pairs.
mouseenterwithmouseoutcombines two sets of rules. Pairmouseenterwithmouseleave, andmouseoverwithmouseout. - Forgetting to clear the color. Without a
mouseleavehandler, the box stays colored after the pointer has gone.
Try it yourself
- Show the two counts in a
preelement under the box, and update them on every event. - Add a
mouseoutlistener that clears the color, alongsidemouseover. Move the pointer onto the bold word. What happens to the color, and why? - Delete the JavaScript and get the same effect with the
:hoverrule from Step 4.