tags:

views:

55

answers:

2

Hi

I want to create a button that has a jQuery click on the fly. After the user is done and hit the button I want to destroy the button and the jQuery click until a time I need it recreated.

I am not sure how to do this in jQuery. I know jQuery.live is an option but I am not sure if this would be better or worse then the way I want to do it.

A: 

This should work. Change html in strings appropriately:

   $('#targetdiv').append( $("<div>foobar</div>").click( function(evt) { $(this).remove(); }))

Here's a demo site showing it in action.

seth
I tried something like that with chaining but it did not work. I tried to put a alert box o n click it never would do anything.
chobo2
odd. I just set up a demo site that works.
seth
when I try the demo and click the button nothing happens.
chobo2
weird. works for me in FF and IE. http://jsbin.com/isowu No errors anything in console?
seth
ah that link works now.
chobo2
+1  A: 

Live would work just fine. If you'd like to avoid using live, you can wire up the the new button as you add it to the DOM.

function addNewButton() {
  $("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />");
  $("#sweetness").click(function() {
    $(this).remove();
  });
}

With live it becomes this:

function addNewButton() {
  $("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />");
}

$("#sweetness").live("click", function() {
  $(this).remove();
});
Andy Gaskell
Does live come with any performance problems if you start using them to much?
chobo2