I have a nested click event listeners and I have a problem, that when I trigger the event listeners multiple times they get looped and send a request x2 times than it should. Where is the mistake in my code? It's probably a beginner's mistake, so I'm very sorry if that's the case. I'm still learning JavaScript and jQuery.
Code:
$('body').on('click', '.color-pick-btn', function() {
id = $(this).data("highlight");
unique = $(this).data("unique");
$(".color-picker").show();
//show the menu directly over the placeholder
$(".color-picker").position({
my: "right top",
at: "right bottom",
of: this,
collision: "fit"
});
$('body').on('click', '.color-picker-item', function() {
color = $(this).data("color");
$.ajax({
type: "POST",
url: '/echo/json',
//data: "highlight=" + id + '&color=' + color + "&unique=" + unique,
data: {
json:'{"highlight":"id","color":"color","unique": "unique"}'
},
dataType: 'json',
}).done(function(data) {
console.log('test');
});
$(".color-picker").hide();
return false;
});
$(document).click(function(event) {
if (!(($(event.target).hasClass('color-pick-btn')) || ($(event.target).hasClass('color-picker-item')))) {
$(".color-picker").hide();
}
return false;
});
return false;
});
JSFiddle here: https://jsfiddle.net/o0r4z6g3/
Check out the console output "test".
Cheers!