Review: DOM events in jQuery
Adding an event listener
You can add an event listener using
on()
: $("#save-button").on("click", function() {
// handle click event
});
If you need to access details about the event, you can find them in the jQuery event object that's passed into the callback function:
$("#face-pic").on("click", function(event) {
var mouseX = event.pageX;
var mouseY = event.pageY;
});
Triggering events
You can manually trigger an event on an object from your JavaScript using trigger:
$("#save-button").trigger("click");
That can be useful when testing new functionality, or when you want some code to run both when the page loads and after some particular event.
Checking DOM readiness
If you want to be sure that the browser does not run your JS code until the DOM is fully loaded and ready, then you can pass your code to
ready()
: $(document).ready(function() {
$("h1").text("Y'all ready for this?");
});
A shorter version of that is to pass your code to the jQuery function:
$(function() {
$("h1").text("Y'all ready for this?");
});
That code is not as readable as the longer version, however, so we recommend using the
ready()
function.Note that if you include your JS in a
<script>
tag at the bottom of the page, then your DOM should be fully ready by the time the browser runs your JS. However, if you want to be doubly sure, then you can choose to always check for DOM readinesss.More event techniques
For a longer summary and deeper dive into jQuery events, read jQuery Event Basics in their documentation.