views:

57

answers:

1

I've been playing with event bubbling and came upon a couple of things new to me...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html onclick="alert('html')" xmlns="http://www.w3.org/1999/xhtml"&gt;
   <head>
     <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
     <title>Frame B Title</title>
   </head>

   <body onclick="alert('Click body')" onload="top.ldfunc(window,'B')" class="Resize" id="idB">
     <p> Body of frame B</p>
     <p>
         <a href="javascript:var display=window.open ('PageC.htm', 'display');">PageC</a> 
     </p>
    <p id="p1" onclick="alert('Click p')"style="color:#00FF00">
some text
       <div  id="IMAGES2" onclick="alert('Click div');">
asdfg
        </div>
more text
     </p>
     <p style="color:red">
red
<p style="color:blue">
blue
</p>
more red
</p>
  </body>
</html>

First I was using div to group some stuff not thinking of it as a paragraph like widgy. I was surprised to find that div and p elements can not be nested. They seem to close out any parent. I have no idea what the DOM tree looks like for this example. Is the "more red" text part of the div?

Second I put an onclick event on the html tag (yes I know it's not mentioned at W3 but thought I'd try it anyway) and was again surprised to see the html event occur before the body event.

BTW, this passes the W3 validation.

  1. Are p and div supposed to work this way?
  2. Can the html tag have an onclick?
  3. Why did the html event happen before the body event?
  4. What do I do to stop the event bubbling at the point I wish to process it?
+2  A: 
  1. p inside a div works fine but it doesn't work the other way round (probably because p is used to hold inline content).

  2. Yes, html tag can have an onclick.

  3. This is sometimes browser-specific. Link in 4. gives details of stopPropagation() method which is a good alternative. Read on cancelBubble property and stopPropagation() to handle bubbling. If you're using jQuery, it's much easier, I think stopPropagation would work fine in jQuery.

  4. Check this (Demos also): http://help.dottoro.com/ljgfjsxd.php

Sidharth Panwar