Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

joyful

mouseenter, mouseleave / mouseover, mouseout 차이점 본문

Javascript

mouseenter, mouseleave / mouseover, mouseout 차이점

조이풀한 개발자 2024. 4. 25. 13:55

 

 

마우스 이벤트 중 moustenter와 mouseover의 차이점을 알아보겠습니다.

 

moustenter와 mouseover는 어떤 요소 안으로 마우스가 들어오는 순간을 감지하는 이벤트이며,

이와 반대로 mouseleave와  mouseout은 마우스가 어떤 요소 밖으로 이동하는 순간을 감지하는 이벤트입니다.

moustenter - mouseleave
mouseover - mouseout

 

 

이 둘은 매우 유사하지만, 이벤트 버블링이 일어나느냐에 따라 차이가 납니다. 

 

*이벤트 버블링: 특정 요소에 이벤트가 발생했을 때 해당 이벤트가 상위의 요소들로 전달되는 특성

 

 

 

 

mouseenter / mouseleave:

-버블링이 일어나지 않습니다.

-따라서 자기 자신만이 이벤트를 받아 한 번만 발생합니다.

 

 

 

mouseover / mouseout:

-버블링이 일어납니다.

-따라서 이벤트가 상위 요소로 전파됩니다.

 

 

 

 

아래 예제 코드 (출처: https://findfun.tistory.com/290) 를 참고하시면 

왼쪽 노란색 박스에 mouseover를 하니 그 부모인 하늘색 박스에도 이벤트가 적용되어 숫자가 증가됩니다.

버블링이 일어난 것이죠. 

반면 오른쪽 노란색 박스에 mouseenter를 하면 그 부모에 영향을 주지 않고 이벤트가 한 번만 발생하는 것을 확인할 수 있습니다.

 

See the Pen MouseOver vs. MouseEnter by KwonWonpyo (@kwonwonpyo) on CodePen.

 

 

 


 

 

 

With deep hierarchies, the number of mouseover events sent can be quite huge and cause significant performance problems. In such cases, it is better to listen for mouseenter events.

(출처: https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event)

 

 

 

 

 

 

결론: 

계층이 많은 구조를 짤 때는 mouseover보다는 mouseenter를 사용하는 것이 효율적일 것 같네요!

 

 

 

 

 

출처: 

https://velog.io/@commi1106/MouseOver%EC%99%80-MouseEnter%EC%9D%98-%EC%B0%A8%EC%9D%B4-%EC%9D%B4%EB%B2%A4%ED%8A%B8-%EB%B2%84%EB%B8%94%EB%A7%81