mouseenter
포인팅 디바이스가 요소의 위치에 있을 때
mouseleave
포인팅 디바이스가 요소를 벗어날 때
mouseenter
와 mouseleave
이벤트는 포인팅 디바이스(마우스, 터치 패드 등)가 요소 위에 있거나 요소를 벗어날 때 발생하는 이벤트입니다.
index.html
<div class="box">box</div>
<p class="desc"></p>
style.css
.box {
display: flex;
align-items: center;
justify-content: center;
width: 500px;
height: 100px;
background-color: #f0f;
font-size: 32px;
font-weight: 700;
}
script.js
window.addEventListener('DOMContentLoaded', function() {
document.querySelector('.box').addEventListener('mouseenter', function() {
console.log('마우스 커서가 box 요소 안에 있음');
document.querySelector('.desc').innerText = '마우스 커서가 box 요소 안에 있음';
});
document.querySelector('.box').addEventListener('mouseleave', function() {
console.log('마우스 커서가 box 요소 벗어남');
document.querySelector('.desc').innerText = '마우스 커서가 box 요소 벗어남';
});
})
mouseover
포인팅 디바이스가 요소의 위치에 있을 때 (이벤트 버블링)
mouseout
포인팅 디바이스가 요소를 벗어날 때 (이벤트 버블링)
mouseover
와 mouseout
이벤트는 포인팅 디바이스(마우스, 터치패드 등)가 요소 위에 있거나 요소를 벗어날 때 발생하는 이벤트로 mouseenter
mouseleave
와 다르게 이벤트 버블링이 일어납니다. 버블링이란, 자식 요소에서 발생한 이벤트가 부모 요소까지 전달되는 것입니다. 예를 들어 버블링이 일어나는 mouseover
의 이벤트 리스너를 부모와 자식 요소 모두에 설정하면, 자식 요소에서 발생한 이벤트가 부모 요소에서도 발생하여 부모 요소의 이벤트 리스너도 함께 실행됩니다. 개발자 모드 열어서 콘솔창에서 확인합니다.
index.html
<div class="content">
content
<div class="content-inner">content-inner</div>
</div>
javascript.js
// 버블링, 캡쳐링이 일어나는 이벤트 타입
document.querySelector('.content').addEventListener('mouseover', function() {
txt('마우스 커서가 content 안에 있음');
});
document.querySelector('.content-inner').addEventListener('mouseover', function() {
txt('마우스 커서가 content-inner 안에 있음');
});
function txt(contentDesc) {
console.log(contentDesc);
}