agyanadda@gmail.com

jQuery Event Delegation

jQuery Forms 1 min read Updated Dec 1, 2026 Topic 18 of 25

The problem

$('.delete').on('click', fn);

This attaches the event only to .delete buttons that exist now. Buttons added later (by AJAX or append) will not work.

The solution: delegation

Attach the event to a parent that always exists and give a selector:

$('#table').on('click', '.delete', function () {
  $(this).closest('tr').remove();
});

The click "bubbles up" to #table, and jQuery checks whether it came from a .delete button.

Benefits

  • Works for future elements
  • One handler instead of hundreds — faster for big tables

trigger()

Run an event from code: $('#refresh').trigger('click');

Namespaced events

.on('click.cart', fn) and later .off('click.cart') removes only your handler.

Example

Example — Editable student table HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>td,th{border:1px solid #ccc;padding:6px} table{border-collapse:collapse;margin-top:10px} tr.done{background:#ebfbee}</style>

<input id="student" placeholder="Student name">
<button id="add">Add student</button>
<table id="table">
  <tr><th>Name</th><th>Action</th></tr>
  <tr><td>Asha</td><td><button class="mark">Present</button> <button class="delete">Delete</button></td></tr>
</table>
<p>Present: <span id="count">0</span></p>

<script>
  $(function () {
    $('#add').click(function () {
      const name = $.trim($('#student').val());
      if (!name) return;
      const $row = $('<tr>').append($('<td>').text(name))
        .append('<td><button class="mark">Present</button> <button class="delete">Delete</button></td>');
      $('#table').append($row);
      $('#student').val('');
    });

    $('#table').on('click', '.mark', function () {
      $(this).closest('tr').toggleClass('done');
      $('#count').text($('#table tr.done').length);
    });

    $('#table').on('click', '.delete', function () {
      $(this).closest('tr').remove();
      $('#count').text($('#table tr.done').length);
    });

    $('#student').on('keyup', function (e) {
      if (e.key === 'Enter') $('#add').trigger('click');
    });
  });
</script>

Add new students — their buttons work because the events are delegated to #table.

Try it Now »

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which code works for buttons added later?

Exercise 2 True / False

Delegation uses event bubbling to a parent element.

Exercise 3 Fill in the Blank

$('#btn').___('click') runs the click event from code.

Frequently Asked Questions

Yes, $(document).on('click', '.btn', fn) always works, but a closer parent is faster and clearer.