■ Front-End ■/JavaScript

[JavaScript] 이벤트 버블링 (Event Bubbling)

한길(One Way) 2023. 2. 28. 05:22

자바스크립트는 객체 기반 함수형 스크립트 언어이며 웹에서 중요한 위치를 차지하고 있다.

 

이벤트 버블링 예제이다. 처음 페이지 로딩한 뒤 적색 부분을 클릭하면 화면 1, 2, 3 순으로 Alert창이 표시된다.

 

 

▣ EventBubbling.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Event Bubbling</title>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR" />
<script type="text/javascript">
//<![CDATA[
 
function mouseDown(nsEvent) {
        var theEvent = nsEvent ? nsEvent : window.event;
        var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
        var theSrc = theEvent.target ? theEvent.target : theEvent.srcElement;
        alert(locString + " " + theSrc);
}
 
document.onmousedown=function (evnt) {
        var theEvnt = evnt? evnt : window.event;
        alert(theEvnt.type);
}
 
window.onload=setupEvents;
 
function setupEvents( ) {
 
        document.getElementById("first").onmousedown=mouseDown;
        document.getElementById("second").onmousedown=function ( ) {
               alert("Second event handler");
        }
}
//]]>
</script>
 
</head>
<body>
<div id="first" style="padding: 20px; background-color: #ff0; width: 150px">
<div id="second" style="background-color: #f00; width: 100px; height: 100px">
</div>
</div>
</body>
</html>

 

▣ 페이지 로딩    


 

▣ 화면 1

 

 

▣ 화면 2

 

 

▣ 화면 3

 

728x90