0

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!

  • Need to see actual code please. – Roamer-1888 Oct 21 '14 at 23:48
  • First thing to do is purge `onclick='removeThisRow()'` from the HTML. Don't try to mix this type of handler attachment with the JavaScript/jQuery way of attaching. The two don't make good bedfellows. – Roamer-1888 Oct 22 '14 at 00:21

2 Answers2

1
$(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

ncubica
  • 8,169
  • 9
  • 54
  • 72
  • @user4167978 This always live, no matter what, I always use it, at least you remove manually the handler, should not go away, actually if you have dynamically elements appearing in you app, this is how you should declare the events for the "future" events. – ncubica Oct 22 '14 at 00:17
  • 1
    @user4167978 in the example above (marked a solution), if you dont have the element #target already in the DOM, the handler will no be attach to the `$("#target")` element because was not declare when the DOM rendered. – ncubica Oct 22 '14 at 00:19
1

Why don't you just run everything in your onClick handler.

$( "#target" ).click(function() {
    $(this).remove();
    //Execute your block of code :)
});
Siva
  • 1,256
  • 3
  • 13
  • 29