# Event listeners

# $(document).ready()

  • In a lot of (older) online examples, you see the jQuery code bundled inside a function within $(document).ready()
    • The ready event becomes active as soon as the entire page is read into the DOM, but the code is executed BEFORE all external files (such as images and external media) are loaded
// long version
$(document).ready(function(){
    // execute jQuery code
    console.log('Document is ready');
});

// shorthand
$(function(){
    // execute jQuery code
    console.log('Document is ready');
});
1
2
3
4
5
6
7
8
9
10
11

REMARK: Do I need the ready event?

  • This depends on where the jQuery code is executed:
    • YES: if the jQuery code is in the head of the document (DOM is not loaded yet)
    • NO: if the jQuery code is just before the closing body tag of the document (DOM is loaded and accessible)
      • Because we use this approach in our example code, we don't need/use the ready event

# Event syntax

  • Just like in vanilla JavaScript, events are always linked to a selector
  • The action (or handler) is written inside a callback function
jQuery vanilla JS
<element>.on('<event>', function(e) { ... }) (opens new window) <element>.addEventListener('<event>', function(e) { ... })
<element>.<event>(function(e) { ... }) (shorthand)

# Default syntax: on()

  • All events (opens new window) can be used with the on() method
  • Example: log a message when the user copied something from the webpage to the clipboard

 




 



// jQuery
$(window).on('copy', function (e) {
    console.log('copy action from JQ initiated');
});

// vanilla JS
window.addEventListener('copy', function (e) {
    console.log('copy action from vanilla JS initiated');
});
1
2
3
4
5
6
7
8
9

# Shorthand version


 




 



// default version
$('h1').on('click', function (e) {
    console.log('user clicked on h1 tag');
});

// shorthand version
$('h1').click(function (e) {
    console.log('user clicked on h1 tag');
});
1
2
3
4
5
6
7
8
9

REMARK: mouseover() vs mouseenter()

There is a big difference between mouseover()/mouseenter() and mouseout()/mouseleave()

  • The mouseover() event is triggered as soon as you hover over the selector, but is also triggered if you hover over descendant elements
  • The mouseenter() event, on the other hand, does not take descendant elements into account
  • Open jQuery/events/mouseOverEnter.html and jQuery/events/mouseOverEnter.js
  • Move the mouse from bottom to top over both sections
    • #div1 with the mouseover event triggers 9 times
    • #div2 with the mouseenter event triggers 1 time

REMARK: hover()

  • The hover() event is the only shorthand version that has two callback functions
    • the first callback function handles the mouseenter event
    • the second callback function handles the mouseleave event
  • Open jQuery/events/hover.html and jQuery/events/hover.js to witness the difference between the two events

# Event on multiple elements

  • Suppose we have multiple buttons with a click event
    • vanilla JavaScript: use this (or e.target) to target the clicked button
    • jQuery: use jQuery's $(this) (or $(e.target)) to target the clicked button
  • Open jQuery/events/this.html and jQuery/events/this.js

REMARK

Note again that (due to the process of implicit iteration in jQuery) you don't need a loop structure to add a similar event listener/handler to multiple selected elements!

# Event on dynamically generated content

  • One of the most common mistakes is adding a wrong event listener to dynamically generated content
  • Open jQuery/events/dynamicContent.html and jQuery/events/dynamicContent.js
  • Click on a span tag inside #section1 or #section2 to create a new span tag at the end of the section
  • But can I also click on a dynamically generated span tag?
    • NO if the span tag is included in the selector to which the click event is linked
    • YES if the selector to which the click event is linked is a real element, and the dynamically generated element is inside this element
  • To add an event listener to a dynamically generated element:
    • The selector to which the click event is linked must be an element that really exists on the page
      • It is best to start from the dynamic element and move up the DOM to find the closest "real" element (in our example the first real element is #section2)
    • Place the dynamic element as an extra parameter between the event and the function inside the event listener

# Event bubbling

  • Use, just like with vanilla JavaScript, e.stopPropagation() to prevent the event bubbling up the DOM tree

 



<element>.click(function (e) {
    e.stopPropagation(); // prevent the event bubbles up the DOM tree
    ...
});
1
2
3
4

# Prevent default action

  • Use, just like with vanilla JavaScript, e.preventDefault() to prevent the default action from being executed

 



<element>.click(function (e) {
    e.preventDefault(); // prevent to open the default URL
    ...
});
1
2
3
4

# Dispatch (trigger) event

  • The trigger() (opens new window) method automatically triggers an event (e.g. .trigger('click'))
  • Also shorthand versions (e.g. .click()) are available
jQuery vanilla JS
<element>.trigger('<event>') (opens new window)
<element>.<event>() (shorthand)
<element>.dispatchEvent(new Event('<event>'))
  • Examples:

 
 


 
 


 
 

// activate the click event on #button1
$('#button1').trigger('click');
$('#button1').click();

// places the cursor in the (text) field #name
$('#naam').trigger('focus'):
$('#naam').focus():

// submit the form with id #form1
$('#form1').trigger('submit');
$('#form1').submit();
1
2
3
4
5
6
7
8
9
10
11

# Arrow functions

  • The jQuery API documentation consistently uses ordinary callback functions for events, but it is perfectly possible to use arrow functions as well
  • Just like in vanilla JavaScript you can't use $(this) (the jQuery equivalent of this in vanilla JavaScript) because the scope is different
    • $(this) refers to the global window object, so you have to use $(e.target) (the jQuery equivalent of e.target in vanilla JavaScript) to refer to the selected element
  • Open jQuery/events/arrowFunctions.html and jQuery/events/arrowFunctions.js

# Examples

# Rotate images

  • Open jquery/events/rotateImages.html and jquery/events/rotateImages.js

# Filter city list

  • Open jquery/events/filterCity.html and jquery/events/filterCity.js

# Reaction test

Last Updated: 5/6/2021, 5:05:24 PM