jQuery HTML Element How to - Handle click event for whole document








Question

We would like to know how to handle click event for whole document.

Answer


<!--   ww w.j a  va2 s.c o m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.6.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){
$(document).click(function(e)
   {
       if($(e.srcElement).attr('id')=='id')
       {
           console.log('click on #id');
       }
       else
       {
            console.log('click on something else'); 
       }
   });
});
</script>
</head>
<body>
  <input id="id" value="click here" type="button">
  <p>or click somewhere else</p>
</body>
</html>

The code above is rendered as follows: