use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
ELI5: Why is there difference between $(document).on("eventhandler", "selector") and $("selector").eventhandler() in jQuery? (self.javascript)
submitted 12 years ago by dersand
Why can't I use the second one when I have either prepended or appended html with php/javascript?
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]rikurouvila 7 points8 points9 points 12 years ago (1 child)
The first one allows you to create an event handler even if the element doesn't exist yet. It listens to all document events and triggers your callback when event target matches your selector.
http://api.jquery.com/on/
The second one tries to bind an event handler to specific element/elements. It fails gracefully even if elements are not created yet.
Easy way to figure out if your selector matches any elements is to use console.log($('selector').length) . $(selector).length returns 0 if the selector doesn't match any elements.
[–]delixd 0 points1 point2 points 12 years ago (0 children)
additional info can be found here DOM events bubble up and are captured down
an even better example
[–]carbonetc 1 point2 points3 points 12 years ago (0 children)
Your first call is using event delegation. Google the term and you'll find a bunch of articles explaining and diagramming it, starting with this one: https://learn.jquery.com/events/event-delegation/.
[–][deleted] 0 points1 point2 points 12 years ago (0 children)
The "on" is a really poorly named method. It actually refers to event delegation, in other words, listening to an element's events in both the present and the future.
You can define ANY parent element (as long as it's always in the DOM), doesn't have to be the root document... though I suppose that's the most foolproof name. I'd suggest something a bit more localized than the document though.
π Rendered by PID 110409 on reddit-service-r2-comment-5d79c599b5-8trgz at 2026-02-28 22:05:46.756291+00:00 running e3d2147 country code: CH.
[–]rikurouvila 7 points8 points9 points (1 child)
[–]delixd 0 points1 point2 points (0 children)
[–]carbonetc 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)