-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
  • 554
  • 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>
Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94
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");
});
MrGeek
  • 21,097
  • 4
  • 28
  • 52
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
  • 29,658
  • 5
  • 35
  • 59
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
  • 30,622
  • 5
  • 73
  • 66
1

You need to add few lines there!

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