jquery / jquery/learn.jquery.com

Expand events tutorials to cover cases where bound elements are removed and re-added.

Open
#624 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
915
Forks
471
PR merge metrics
No merged PRs in 30d

Description

Originally filed in jquery/api.jquery.com#632.

There seems to be pretty regular confusion surrounding the notion that event bindings break if the element you bound to was removed from the document (via, say, .remove()) and then re-added (like when you create a new element with $()).

The specific issue is that people think that simply using a delegated listener is enough - e.g.:

$('.someDiv').on('click', '.someChild', function() {
    $('.someDiv').remove();
});

They then later re-add $('.someDiv') and expect this to work because the handler is technically bound to an element that exists at the time of binding - it just happened to be removed and re-added.

The .remove() docs helpfully explain that:

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

This is fine, except that a lot of people aren't going to think to go to docs for .remove() while reading about events. This also doesn't cover cases where somebody ran something like .html('<span>no cookie for you</span>') on a parent of the bound node, wiping it out.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the existing events tutorials and the .remove() documentation, using the delegated .on('click', '.someChild', ...) example as the motivating case. Expand the tutorials to explain what happens when bound elements are removed and re-added, including removal through .html(), and make clear when .detach() preserves handlers.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.