Reputation: 2263
I'm trying to remove an image element if clicked, which is added dynamically using jquery. The achievement is a simple pinned map like image app.
HTML:
<div class="imageMapContainer" style="position:relative;" >
<img class="imageMap" src="image.jpg" style="position:relative;" width="300px" height="300px" />
</div>
Javascript:
$(".imageMap").click(function(e){
var offset = $(this).offset();
var posLeft = e.clientX - offset.left;
var posTop = e.clientY - offset.top;
var pin = "<img onClick='javascript:removePin();' class='imgPin' src='pin.png'" + "style='width:auto;height:auto;position:absolute;left:" + posLeft + ";top:" + posTop + ";' />";
$(".imageMapContainer").append(pin);
});
function removePin(){
//couldn't figure out here
}
I've tried a lot of things but, not a talented jscript guy I am I guess. thanks in advance.
Upvotes: 0
Views: 113
Reputation: 8346
Use .on
$('.imageMapContainer').on('click', '.imgPin', function() {
$(this).remove();
});
Upvotes: 0
Reputation: 15213
In your click event you can add this
to send a reference to the clicked element.
You can than use that reference in your removePin
function like:
$(".imageMap").click(function (e) {
var offset = $(this).offset();
var posLeft = e.clientX - offset.left;
var posTop = e.clientY - offset.top;
var pin = "<img onClick='javascript:removePin(this);' class='imgPin' src='pin.png'" + "style='width:auto;height:auto;position:absolute;left:" + posLeft + ";top:" + posTop + ";' />";
$(".imageMapContainer").append(pin);
});
function removePin(elm) {
$(elm).remove();
}
Upvotes: 1