event bubble Classic Example


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <html onclick="revealEvent('html',event)">
  2. <head>
  3. <title>Event Cancelling & Redirecting</title>
  4. <script type="text/javascript">
  5. <!--
  6. //window.onload=init;
  7. // display alert with event object info
  8. function revealEvent(elem,evt) {
  9. evt = (evt) ? evt : ((window.event) ? window.event : "")
  10. if (evt) {var elemx = (evt.target) ? evt.target : evt.srcElement;}
  11. var elemv = (evt.currentTarget) ? evt.currentTarget.nodeName : document.activeElement.tagName;
  12. var msg="Event (from "+elemx.tagName+" | "+elemv+" at ";
  13. msg += evt.clientX+","+evt.clientY+") is now at the <";
  14. msg += elem+"> element.";
  15. alert (msg);
  16. }
  17. function init(){
  18. document.onclick = docEvent;
  19. document.body.onclick = docBodEvent;
  20. }
  21. function docEvent(e) {
  22. revealEvent("document",e);
  23. }
  24. function docBodEvent(e) {
  25. revealEvent("Body",e)
  26. }
  27. function buttonEvent(form,e){
  28. revealEvent("button",e);
  29. // cancel if checked (ie4+)
  30. e.cancelBubble = form.bubbleCancelState.checked;
  31. // redirect if checked (ie5.5+)
  32. if (form.redirect.checked) {
  33. document.body.fireEvent("onclick",e);
  34. }
  35. }
  36. //-->
  37. </script>
  38. </head>
  39. <body onload="init()" >
  40. <h1>Event Cancelling &amp; Redirecting</h1>
  41. <hr/>
  42. <form onclick="revealEvent('form',event)">
  43. <p><button name="main1" onclick="buttonEvent(this.form,event)">Button 'main1'</button></p>
  44. <p>
  45. <input type="checkbox" name="bubbleCancelState" onclick="event.cancelBubble=true" />Cancel Bubbling at button<br/>
  46. <input type="checkbox" name="redirect" onclick="event.cancelBubble=true" />Redirect Event to body
  47. </p>
  48. </form>
  49. </body>
  50. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.