Trần Minh
Trần Minh

Reputation: 1673

Error in using contextmenu in jquery?

I want to create a contextmenu of a div tag to append some contents into it. But when i right click many times continuously,my div tag contains more contents than i want.Here is my code.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<style type="text/css">
#container{
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
#MyMenu{

position: absolute;
border: 1px solid blue;
}
</style>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#container').bind('contextmenu',function(e){
e.preventDefault();
var x=e.pageX;
var y=e.pageY;
$('#MyMenu').css({'top': y+'px','left': x+'px'}).show();
$('#add').click(function(e){
  var ContentToAppend='<p>My Content</p>';
  $('#container').append(ContentToAppend);  
});
}); 
});
</script>

</head>

<body>

<div id="container">

</div>
<ul id="MyMenu">
<li><a href="#" id="add">Add</a></li>
<li><a href="#" id="del">Delete</a></li>
</ul>
</body>

</html>

For example,if i right click 5 times continuously,in my div will contain 5 lines "My Content" although i only want 1 line.Can anyone explain why and solution for me?Thank a lot!

Upvotes: 0

Views: 1035

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

Try (See DEMO):

$(document).ready(function(){
  $('#container').bind('contextmenu',function(e){
    e.preventDefault();

    var x=e.pageX;
    var y=e.pageY;

    $('#MyMenu').css({'top': y+'px','left': x+'px'}).show();
  }); 

  $('#add').click(function(e){
    var ContentToAppend='<p>My Content</p>';
    $('#container').append(ContentToAppend);  
  });
});​

The deal is that in your version you bind to #add element click event hendler each time user open context menu. So after 5 times it heppens there will be 5 click event hendlers, so if you then click on #add element you add '<p>My Content</p>' string to #container element 5 times.

Upvotes: 1

Related Questions