Reputation: 2515
I have implemented a context menu on right click. On my menu, I have a button, on pressing it I console.log("button is clicked");
message.
the problem I am facing is, first time on clicking, I am getting message 1 time. on the second time, on a single click, I am getting message 2 times. and so on like this...
Below is my jquery code:
$(document).on("contextmenu", function(event) {
if ($(event.target).hasClass("sim-row-edit")) { // sim-row-edit ended
console.log("right click identified");
.....
// no problem in here
// multiple occurance problem coming here
$(".custom-menu li").click(function() {
switch ($(this).attr("data-action")) {
case "firstcase":
var thisDiv = target_element.closest('div');
console.log("Button is clicked");
break;
case "nextcase":
...
$(document).on("mouseup", function() {
$(".selected").removeClass("selected");
$(".custom-menu").hide(100);
});
html code:
<ul class='custom-menu'>
<li data-action = "first">Clone</li>
<li data-action = "second">Remove</li>
<li data-action = "third">Edit</li>
</ul>
How do I get rid of this problem?
Upvotes: 0
Views: 79
Reputation: 2575
$(document).on("contextmenu", function(event) {
if ($(event.target).hasClass("sim-row-edit")) { // sim-row-edit ended
console.log("right click identified");
.....
// no problem in here
// unbind click handler to avoid multiple occurance problem
$(".custom-menu li").unbind('click');
$(".custom-menu li").click(function() {
switch ($(this).attr("data-action")) {
case "firstcase":
var thisDiv = target_element.closest('div');
console.log("Button is clicked");
break;
case "nextcase":
...
$(document).on("mouseup", function() {
$(".selected").removeClass("selected");
$(".custom-menu").hide(100);
});
Just unbind the previos click handler before adding handler again.As of jQuery 3.0, .unbind()
has been deprecated. It was superseded by the .off()
Upvotes: 0
Reputation: 1357
try this event.stopPropagation()
:
$(".custom-menu li").click(function(e) {
e.stopPropagation();
switch ($(this).attr("data-action")) {
case "firstcase":
var thisDiv = target_element.closest('div');
console.log("Button is clicked");
break;
case "nextcase":
...
ref : https://api.jquery.com/event.stoppropagation/
Upvotes: 1