- Part 1: Adding and Loading the Library
- Part 2: Using Selectors
- Part 3: Reacting to Events
- Part 4: Ajax
Reacting to Events
Beyond finding and changes elements, jQuery also supports a robust set of functions for listening and reacting to events within a browser. While most browsers have the standard addEventListener(), jQuery has shortcuts and quick functions for accessing the common tasks associated with dealing with events.
One of the most commonly-used functions for listening for events is the on() function in jQuery. It works through supplying the event (as a string) and then a function to run when that event happens.
Frequently, although not always, an anonymous function will be used with on() to act on the event. Within this function, other selectors and actions can take place. For the situations where the result of the selector is needed, the this keyword can be wrapped in the selector function, $(), to make it a jQuery object.
To change the text content of the element(s) on which the on() function had been used, for example, it would be the following: $(this).text().
The function one() acts like the function on(), but only runs at most once. For the situations where a single event or action needs to happen, this is a very useful shortcut.
Click() and Other Events
To help with the common tasks of listening for certain events, jQuery has shortcut versions of many events like click() and keypress(). These are used like on() and one(), but do not have the first parameter of listing the event. The name of the function itself signals for which event it is used.