Reputation: 3
My question is as follows:
I have a dynamically generated element that has onclick='removeMe()', a function that causes it to removes itself.
I used jQuery .on('click',selector,handler) delegation to bind a function to this element, to execute a specific block of code.
However, the element removes itself and in doing so deletes the handler that would execute that block of code.
To spice things up: the block of code must be run after the element is removed, and I cannot edit the function that removes the element to execute my code after.
I'm new to jQuery, so the first solution that popped into my head was to somehow bind the handler to another element that is never removed, which runs when the first element is clicked. Is that possible?
Are there any other, better solutions I haven't thought of? Am I missing something obvious?
If my explanation is not clear I can provide clarification or provide the actual situation in which this takes place.
Thanks in advance!
Edit: Answered by Sivapriyan, and that solution is exactly what I needed. Thank you!
Upvotes: 0
Views: 192
Reputation: 1276
Why don't you just run everything in your onClick handler.
$( "#target" ).click(function() {
$(this).remove();
//Execute your block of code :)
});
Upvotes: 1
Reputation: 8495
$(document).on("click",".selector",function(){
alert("I will always live");
});
Declare in that way and you handler will always a live. Now the handler is on the document and no on the $element
Upvotes: 1