Events
Similar to vanilla JavaScript, we can add event handlers to different elements on the page using jQuery event handler functions like .click(), .submit(), etc, or using .on([insert event type here], [insert function here]).
More on jQuery events here: https://api.jquery.com/category/events/
Event Delegation
Event delegation attaches an event to a single element and delegates the events out to specified children. This is important for non-static collections of elements.
In the above code, the 4th list item wouldn't have an event handler attached to it! This event delegation will fix it:
Event delegation makes things easier by applying the event to the entire parent for delegation to all children as they are born.
Effects and Animations
While this works for a static list, if we were to add another list item later, it would not have an event listener attached unless we ran this function again. Event delegation makes things easier by applying the event to the entire parent which in turn delegates the event to its children as they are born.
See the Pen Event Delegation by Brian Hague (@bhague1281) on CodePen.
Event Propagation
This occurs when there is an element nested within another element and both of them have event handlers attached to them, so the firing of an event attached to the internal element triggers the firing of the event handler attached to its parent elemennt.
See the Pen Event Propagation by Brian Hague (@bhague1281) on CodePen.
Making sure the DOM has loaded
Using vanilla JS, we used:
But using jQuery, we can use:
Last updated