I have this code which adds markers on a jpg map dynamically based on where you click on the map image. It creates the ids dynamically as well. I am trying to attach a click event to every dynamically created marker so that if the user clicks on the marker it will be deleted. The problem is that when they click on the marker it generates another marker. I want the user to be able to place the marker on the map by clicking on the map and then if they want to delete the marker they can click on it again without generating a new marker when they click on the marker they want to delete.
Thank you in advance for all your help.
JS :
$(document).ready(function(){
var clicks = 0;
$("#container").click(function(e) {
e.preventDefault();
var x = e.pageX - 38;
var y = e.pageY - 60;
var img = $('<img>');
img.css('top', y);
img.css('left', x);
img.css('width',60);
img.css('height',60);
img.attr('src', 'images/location-marker1.png');
img.attr('id', 'marker' + clicks);
img.attr('class', 'marker' + clicks);
img.appendTo('#container');
$("#container").on("click", "img.marker" + clicks, function(){
var id = $(this).attr('id');
alert(id);
$(this).remove();
});
clicks += 1;
})
});
HTML :
<div id="container">
<img src="images/floorplan1_fs.jpg">
</div>
imgto the container. Try adding an event argument to yourimgclick handler and callingevent.stopPropagation()... developer.mozilla.org/en/docs/Web/API/Event/stopPropagation