I have a clickable <div>
, in which I am adding <img>
tags using jQuery.
All the <img>
tags have the same id
.
I want to click on the inserted image and handle the event for that element, but I get the <div>
's event handler, instead.
I have tried e.preventDefault()
and e.stopImmediatePropagation()
both on the <div>
and added images, but it is not working.
Javascript:
$(document).ready(function () {
$("#container").click(function (e) {
debugger;
e.preventDefault();
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var img = $('<img>');
img.css('top', y);
img.css('left', x);
img.attr('id', 'marking');
var selectedItem = $('#markerItem').val();
if (selectedItem == 'b') {
img.attr('src', 'broken.png');
}
else if (selectedItem == 'd') {
img.attr('src', 'damage.png');
}
else if (selectedItem == 's') {
img.attr('src', 'scratch.png');
}
else if (selectedItem === null || selectedItem === undefined || selectedItem === "") {
img.attr('src', 'damage.png');
}
img.appendTo('#container');
}),
$("#marking").click(function (e) {
debugger;
e.stopImmediatePropagation();
$('img[id$="marking"]').remove();
})
});
HTML:
<div id="container">
<img src="" height="475" width="600" alt="Image preview..." id="img1">
</div>