# 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
- The
// 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
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
- Because we use this approach in our example code, we don't need/use the
- YES: if the jQuery code is in the
# 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
2
3
4
5
6
7
8
9
# Shorthand version
- For some frequently used events there is also a shorthand version available
- Mouse events:
click()
(opens new window),dblclick()
(opens new window),mousedown()
(opens new window),mouseenter()
(opens new window),mouseleave()
(opens new window),mousemove()
(opens new window),mouseout()
(opens new window),mouseover()
(opens new window),mouseup()
(opens new window),hover()
(opens new window) - Keyboard events
keydown()
(opens new window),keypress()
(opens new window),keyup()
(opens new window), - Form events:
blur()
(opens new window),change()
(opens new window),focus()
(opens new window),focusin()
(opens new window),focusout()
(opens new window),select()
(opens new window),submit()
(opens new window) - Screen events:
resize()
(opens new window),scroll()
(opens new window)
- Mouse events:
// 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
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 themouseover
event triggers 9 times#div2
with themouseenter
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
- the first callback function handles the
- 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
(ore.target
) to target the clicked button - jQuery: use jQuery's
$(this)
(or$(e.target)
) to target the clicked button
- vanilla JavaScript: use
- 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 newspan
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 theclick
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
- NO if the
- 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
)
- 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
- Place the dynamic element as an extra parameter between the event and the function inside the event listener
- The selector to which the
# 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
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
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
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 ofthis
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 ofe.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
- Open jquery/events/reaction.html and jquery/events/reaction.js
- This example is the jQuery version of the previous example written in vanilla JavaScript:
https://itf-es6.netlify.app/es6/timing/reaction.html (opens new window)
READING TIP