Search code examples
javascriptdom-eventsevent-bubbling

Why bubbling is non-functional


I just want to understand how capturing and bubbling work.

Unfortunately this code just work in IE, and not working in Firefox.

When I click on div3, it just stop there; it is not bubbling up toward body element. Can somebody enlighten me?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript">

var addEvent = function(elem, event, func, capture){
    if(typeof(window.event) != 'undefined'){
        elem.attachEvent('on' + event, func);
    }
    else{
        elem.addEventListener(event, func, capture);
    }
}


var bodyFunc = function(){
    alert('In element body')
}

var div1Func = function(){
    alert('In element div1')
}

var div2Func = function(){
    alert('In element div2')
}

var div3Func = function(){
    alert('In element div3')
}


var init = function(){
    addEvent(document.getElementsByTagName('body')[0], 'click', bodyFunc, true);
    addEvent(document.getElementById('div1'), 'click', div1Func, true);
    addEvent(document.getElementById('div2'), 'click', div2Func, true);
    addEvent(document.getElementById('div3'), 'click', div3Func, true);
}


addEvent(window, 'load', init, false)


</script>
</head>

<body>

<h1>Using the Modern Event Model</h1>

<div id="div1" style="border:1px solid #000000;padding:10pt;background:cornsilk">

    <p>This is div 1</p>
    
    <div id="div2" style="border:1px solid #000000;padding:10pt;background:gray">
    
        <p>This is div 2</p>   
         
        <div id="div3" style="border:1px solid #000000;padding:10pt; background:lightBlue">
            <p>This is div 3</p>
        </div>
        
    </div>
    
</div>


</body>

</html>

Solution

  • I'm not sure exactly what you are seeing, but when I open the page in FF3.6 on Win7 and click on div 3, I see what I would expect: "In element body", then div1, then div2 and finally div3. In other words, I see the alerts in capturing order.

    You are seeing bubbling in IE because, AFAIK, IE only does bubbling and never does capturing.

    You should be seeing capturing in FF, because you are telling the events to listen in capturing mode by passing "true" as the last parameter of the 4 addEvent calls. Change those four to "false" and you will see bubbling order.