Events and Behaviour

An event in HTML is triggered by certain things that the user does, or that happens in the browser. For example, the “click” event occurs when the user clicks on the element. In the example above, you can click on the paragraph and it triggers execution of some JavaScript logic.

There are several other events on elements and we will use some of then as the course goes on. For example, there are events “mouseover” (when the mouse cursor moves over an element, on a desktop computer), “load” (when the page has finished loading), “touchstart” (the user starts touching an element, on a mobile device), and “change” (the user changes the entry in a form element). We will introduce more event types as they are needed.

The value for the event property (say_hello() in the example) is a piece of JavaScript code. It will usually be short and used to call longer pieces of logic written elsewhere. In this example, it calls the say_hello function defined in the JavaScript file.

jQuery Events

In the previous section, we saw the jQuery style of attaching functions to events:

jQuery(…).click(some_function)

We will continue to work with the jQuery style: it keeps the behaviour stuff isolated in the JavaScript file where it belongs, instead of mixing it in the HTML. (There are also a few other reasons it's better, but we won't discuss them here.)

Other Events

There are several other events that we can access with jQuery.

For example, the .mouseenter and .mouseleave functions can be used to call a function when the use moves their mouse cursor over/away from an element. A more complete example of using these:

mouse_arrived = function() {…}
mouse_left = function() {…}
setup = function() {
  jQuery('#hoverable').mouseenter(mouse_arrived)
  jQuery('#hoverable').mouseleave(mouse_left)
}
jQuery(document).ready(setup)

It's worth noting that these events aren't very meaningful for a touch device (phone or tablet). You need to be a little bit careful and think about whether or not your users can actually do the things required to trigger important events.

There are even more event types than are accessible this way in jQuery. In fact, the functions we have seen like .click and .mouseenter are actually shortcuts for the .on function. These two lines of code are exactly equivalent:

jQuery('p').click(handle_click)
jQuery('p').on('click', handle_click)

You can use .on to connect some other event types like this:

jQuery(document).on('scroll', user_scrolled)
jQuery('p').on('touchstart', handle_touch)

You probably won't have to use this technique for this course, but it's worth remembering that there's more interaction potential out there.

Example

Needs an example: maybe mouseenter/mouseleave.