0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank i used this code.If i have many div tags with class=container instead of id=container.How can i use this contextmenu to append content into each div tag(class=container) i right click.
I think var ContentToAppend in scope $('#add').click().So why it appears 5 times although i click Add 1 time.
Oh i see.Understand.Thank so much.If i have many div tags with class=container instead of id=container.How can i use this contextmenu to append content into each div tag(class=container) i right click.Thank for your solution.
Thank so much, Speransky Danil!
Oh.I am new member.How can i do that.I can't find it on my question properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.