jQuery Event How to - Check clicked element id








Question

We would like to know how to check clicked element id.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.0.2.js'></script>
<style type='text/css'>
#test {<!--from   www . j a  v  a2 s.co m-->
  background-color: red;
  width: 200px;
  height: 200px;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $(document).ready(function(){
        $(document).click(function(e){
           if(e.target.id == 'test')
           {
               console.log('Red box clicked!');
           }
           else
           {
               console.log('Clicked something else');
           }
        })
    });
});
</script>
</head>
<body>
  <div id="test"></div>
</body>
</html>

The code above is rendered as follows: