locked
hit test RRS feed

  • Question

  • Hello

    I have a div that contains some other tags.

    I want to fire an event when the mouse is clicked on the div.

    But if in that pouint there is another tag I do not want to have that event fired.

    what is the best approach?

    Thursday, May 3, 2012 7:45 AM

All replies

  • In the example below, the event handler assigned to the parent node for the onclick event checks which node fired the event - if it is the unwanted one, "return false" is used, else ...

    Also, if it is an onclick event, set the cursor attribute to "pointer" for the parent and to "default" for the node you don't want to fire the event - to give an indication to the user which content is active.

    <!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" lang="en">
    <head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
    <!--
    body {width:100%;background:#999;color:#000;text-align:center;margin:0;padding:20px;font:bold 14px/18px Arial;}
    #divRel {width:300px;height:200px;margin:0 auto;background:#777;cursor:pointer;}
    #box1 {width:200px;height:80px;margin:0 auto 30px;padding-top:30px;background-color:#ff0;cursor:default;}
    #box2 {width:300px;height:25px;margin:10px auto 0;padding-top:5px;background-color:#ccc;}
    -->
    </style>
    <script type="text/javascript">
    function fx(){
     var t=null;
     document.getElementById("divRel").onclick=function(e){
      var target;
      e=e||event;//handle non-IE || IE
      target=e.target||e.srcElement;//again handle non-IE || IE
      if(target===document.getElementById("box1")){
       return false;
      }
      else{
       clearTimeout(t);
       document.getElementById("box2").innerHTML="Event fired";
       t=setTimeout(function(){document.getElementById("box2").innerHTML="";},2000);
      }
     };
    }
    </script>
    </head>
    <body onload="fx()">
    <div id="divRel">
    <div id="box1">Click the yellow box and nothing happens</div>
    Click the dark gray area and fire the event
    </div>
    <div id="box2"></div>
    </body>
    </html>

    Thursday, May 3, 2012 9:20 AM