jQuery Event How to - Attach a right click event to a div








Question

We would like to know how to attach a right click event to a div.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--from  www .  j  a va 2  s.c om-->
<body>
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
    $('body').ready(function() {
        $('#divParent').on('contextmenu', function(event) {
            console.log($(event.target).attr('id'));
        });
    });
</script>
<body>
  <div id="divParent">
    click parent
    <div id="divChild">click child</div>
  </div>
</body>
</html>

The code above is rendered as follows: