-1

I am new to jquery, I have a button click event which works well but when i use the append() to append the button inside div. The click event doesn't work

My code below:

$('#button').click(function() {
    alert('works');
    $('#element').show("slow");
});
Seb Cooper
  • 564
  • 2
  • 13

5 Answers5

7

You have to use jQuery event-delegation:-

$(document).on('click', "#button", function() {
  alert('works');
  $('#element').show("slow");
});

Working example:-

$('#append_button_dynamically').append("<button id='button'>ClickMe</button>");

$(document).on('click', "#button", function() {
  alert('works');
  $('#element').show("slow");
});
#element{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="append_button_dynamically"></div>

<div id="element">This is hide but will show on button click</div>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
6

Because the button is dynamically created, it cannot be triggered by “itself”, instead, trigger it through a static element, such as <body> :

$('body').on('click', '#button', function() {
    alert('works');
    $('#element').show("slow");
});
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
2

Your code must work. You might have forgotten to include the JQuery file. Check the attached code snippet.

$('#container').append("<button id='button'>Button</button>");
$('#button').click(function() {
    alert('works');
    $('#element').show("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'>Button here</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

You're likely doing that before the element exists in the DOM. You should probably have your scripts right before the </body> instead of in the <head> tag.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
1

You need to add few lines there!

$(document).ready(function(){
     $('#button').click(function() {
          alert('works');
          $('#element').show("slow");
     });
});
JaTurna
  • 194
  • 14