1
<button id="first">Click me first</button>

$('#first').click(function(){
  $('body').append('<button id="second">Now click me</button>');
});

$('#second').click(function(){
  $(this).hide();
});

jsFiddle

When #first is clicked, #second gets appended. When #second gets clicked, I want it to hide itself.

Why isn't this working?

UserIsCorrupt
  • 4,469
  • 14
  • 37
  • 41

6 Answers6

4

When you initiate this event handler

 $('#second').click(function(){
  $(this).hide();
});

'#second' element doesn't exist yet. Later you add the element but that element doesn't initiated with any event handler.

You can try this

$('#first').click(function(){
  $('body').append('<button id="second">Now click me</button>');
  // event handler will attached for already exist '#second' element
  // attach event if only #second doesn't have event yet
  if(!($('#second').data('events') != null && $('#second').data('events').click != undefined && $('#second').data('events').click.length == 1))
  $('#second').click(function(){
    $(this).hide();
  });
});
Jon Kartago Lamida
  • 817
  • 1
  • 7
  • 12
2

Use jQuery on function.

$(document).on('click', '#second', function(){
  $(this).hide();
});
Arvind Bhardwaj
  • 5,174
  • 5
  • 33
  • 48
1

It's not working because $('#second') does not match anything when it gets executed.

Try assigning the click handler to the element before adding to the DOM:

$('#first').click(function(){
  var $button = $('<button id="second">Now click me</button>');
  $button.click(function() {
    // handler
  });
  $('body').append($button);
});

You can also use on to delegate the event if you need to 'attach' the event handler before the element exists.

Flash
  • 14,775
  • 13
  • 67
  • 94
1

use on()

$(document).on('click', '#second', function(){
  $(this).hide();
})

refer

http://api.jquery.com/on/

Kanishka Panamaldeniya
  • 16,732
  • 29
  • 117
  • 190
0

try

$('#second').on("click",function(){
 $(this).hide();
});
Dnyan Waychal
  • 1,420
  • 11
  • 27
0

To clarify why your code is not working : During the definition of the event handling of #second that div doesn't exist. You should define the event handling after you are sure that the DOM element $("#second") is present in the page.

Manish Mulani
  • 6,687
  • 9
  • 41
  • 45