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,837
  • 15
  • 38
  • 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
  • 827
  • 1
  • 7
  • 12
2

Use jQuery on function.

$(document).on('click', '#second', function(){
  $(this).hide();
});
Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49
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
  • 15,945
  • 13
  • 70
  • 98
1

use on()

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

refer

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

Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
0

try

$('#second').on("click",function(){
 $(this).hide();
});
Dnyan Waychal
  • 1,418
  • 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
  • 7,125
  • 9
  • 43
  • 45