jQuery Basics: Part 3: Reacting to Events

jQuery Basics

jQuery is a JavaScript library designed to simplify the processes of traversing and manipulating elements in client-side HTML. It is an open source library commonly found on many sites.


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.

On()

Screenshot 2018-10-24 14.17.49

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().

One()

Screenshot 2018-10-24 14.27.32

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

Screenshot 2018-10-24 14.34.52

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.

Play with the example on Repl.it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s