JavaScriptのmouseenterとmouseleaveイベントは、ユーザーのマウスカーソルが特定の要素に入ったり、離れたりしたときに発生するイベントです。これらはmouseoverとmouseoutに似ていますが、いくつかの重要な違いがあります。今回は、それぞれの基本的な使い方から応用例までをまとめていきたいと思います。
mouseenterイベントは、マウスカーソルが要素の上に入ったときに発生します。このイベントは、子要素にカーソルが移動しても再度発生することはありません。そのため、親要素と子要素間のイベントバブリングを回避することができます。
一方、mouseleaveイベントは、マウスカーソルが要素の上から完全に離れたときに発生します。こちらも、子要素から親要素への移動では発生しない点が特徴です。
以下の例では、マウスカーソルが要素に入ったり離れたりする際に色を変えるシンプルなスクリプトを紹介します。
See the Pen Untitled by tones (@tonescodedesign) on CodePen.
const box = document.getElementById('box');
box.addEventListener('mouseenter', () => {
box.style.backgroundColor = 'lightgreen';
box.textContent = 'マウスが入りました';
});
box.addEventListener('mouseleave', () => {
box.style.backgroundColor = 'lightblue';
box.textContent = 'マウスが離れました';
}); <div id="box">マウスを重ねてみてください</div>#box {
width: 200px;
height: 200px;
background-color: lightblue;
text-align: center;
line-height: 200px;
font-size: 15px;
transition: background-color 0.3s;
}このコードでは、mouseenterとmouseleaveイベントを使用して、ボックスの背景色とテキストを変更しています。mouseoverやmouseoutと異なり、イベントバブリングが発生しない点が特徴です。
以下の例では、マウスカーソルが画像の上に来たときに拡大し、離れたときに元のサイズに戻るズーム効果を実現します。
See the Pen mouseenter() / mouseleave() by tones (@tonescodedesign) on CodePen.
const image = document.getElementById('image');
image.addEventListener('mouseenter', () => {
image.style.transform = 'scale(1.2)';
});
image.addEventListener('mouseleave', () => {
image.style.transform = 'scale(1)';
});<div id="container">
<img id="image" src="https://placehold.jp/300x200.png" alt="サンプル画像">
</div>#image {
display: block;
width: 300px;
height: 200px;
transition: transform 0.3s ease;
}
#container {
overflow: hidden;
display: inline-block;
}このコードでは、mouseenterイベントで画像を拡大し、mouseleaveイベントで元に戻すアニメーションを実装しています。
以下は、マウスカーソルが通知要素から離れたときに自動で非表示にする例です。
See the Pen mouseenter() / mouseleave() by tones (@tonescodedesign) on CodePen.
const notification = document.getElementById('notification');
const showNotification = document.getElementById('showNotification');
showNotification.addEventListener('click', () => {
notification.style.display = 'block';
});
notification.addEventListener('mouseleave', () => {
notification.style.display = 'none';
});<button id="showNotification">通知を表示</button>
<div id="notification">この通知はマウスを離すと消えます</div>#notification {
width: 300px;
padding: 20px;
background-color: lightcoral;
color: white;
text-align: center;
position: fixed;
top: 20px;
right: 20px;
display: none;
}このコードでは、ボタンをクリックして通知を表示し、マウスカーソルが通知から離れたときに非表示にしています。
- mouseenter: 子要素へのカーソル移動でイベントが再発生しないため、親要素単位での操作に適しています。
- mouseleave: 親要素から完全にカーソルが離れたタイミングを検知する場合に適しています。
これらを適切に使い分けることで、意図したインタラクションをより簡単に実現することが可能です。
JavaScriptのmouseenterとmouseleaveイベントは、ユーザーのマウス操作に基づいたインタラクションを簡単に実現するための便利なツールです。mouseoverやmouseoutと似ていますが、イベントバブリングの影響を受けないため、より直感的に扱うことができます。

