WEEK: 7
Active: March 21st - April 5th
Note: Spring Break runs from the March 24th - April 1st
Work Due: April 6th @ 8:00AM

Events

Browsers and the DOM API implement an “Event Interface”. The Mozilla Developer Network describes this interface in the following way;

The Event interface represents any event which takes place in the DOM; some are user-generated (such as mouse or keyboard events), while others are generated by APIs (such as events that indicate an animation has finished running, a video has been paused, and so forth). There are many types of events.

Alternatively, w3schools describes events as follows;

HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).

Essentially, an event is something that has occurred on or in a webpage. Browsers allow developers to use JavaScript to register callback functions that are to be executed when specific events occur.

Button “Click”

Perhaps the simplest event to demonstrate this concept with is a button “click”.

In the following HTML file, a single button is created. The onclick= attribute is added to this element. This attribute is supplied a callback function, in this case, popup(). This function simply creates an alert popup.

Please press the button to execute the supplied function.

[ Code Download ] [ View on GitHub ] [ Live Example ]

onclick= attribute

The onclick= attribute can be applied to any DOM element and allows developers to attach a callback function to be executed when a click event occurs with the specified element.

In the following example, clicking on the example alternates the background color of the example page.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Attaching Events to DOM Elements

In addition to defining events through HTML element attributes, you can also attach event listeners to elements with JavaScript using the query selectors. In the following example, an event is attached to a Button element. To do this, a reference to the element is bound to a variable. This reference can then be used to attach an event with a reference method. As with the style methods, these tend to be based off of, and similar to the attributes that would be used in HTML (although they are sometime slightly different).

For our current example, we will use the onclick = method.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Best Practices

It is considered a best practice to use JavaScript to set event handlers. This is to keep you HTML document and content separate from your scripts and code. By keeping these separate, it will be easier for you to debug, understand what is happening, and trace lines through your code. You are heavily encouraged to use JavaScript to set event handlers for the purposes of this course.

To make things even more confusing (or not…), I am instead going to ask you to only use the following methods for setting events.

addEventListener()

The most recent, and currently “best practice” technique for adding event listeners to elements is with the .addEventListener() method, which can be called on any element. This method allows you to supply two properties;

  1. A type of event to listen for (i.e. click, focus, mouseover).
    • Please note: This is supplied as a string.
  2. The function to execute.
    • This is a callback function, therefore, you can supply a full function definition, or a function name without the function operator (i.e. no parentheses).

As an example of this method, we will use the background color example from above, and rewrite it.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Another example shows the use of .addEventListener() to attach a function to a button that then shows and hides elements.

Notice that these elements are all written into the HTML document. These are then hidden by default using the hidden attribute (i.e. hidden="true"). This allows for content to remain in the HTML document, and keep the JavaScript document as a place for code logic.

For your homework this week, this is a good organizational approach to take…

[ Code Download ] [ View on GitHub ] [ Live Example ]

Move to click from onclick

Notice how the event name is now “click” instead of “onclick”!

The click event listener is designed for modern browsers that might also include touch screens. This event listener provides an interface to additional property values about an element assigned the event.

These include (Some of these may not yet make sense to you. Skim this list for those that do.);

  • target
    • EventTarget
    • The event target (the topmost target in the DOM tree).
  • type
    • DOMString
    • The type of event.
  • bubbles
    • Boolean
    • Whether the event normally bubbles or not
  • cancelable
    • Boolean
    • Whether the event is cancellable or not
  • view
    • WindowProxy
    • document.defaultView (window of the document)
  • detail
    • long
    • A count of consecutive clicks that happened in a short amount of time, incremented by one.
  • currentTarget
    • EventTarget
    • The node that had the event listener attached.
  • relatedTarget
    • EventTarget
    • For mouseover, mouseout, mouseenter and mouseleave events: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
  • screenX
    • long
    • The X coordinate of the mouse pointer in global (screen) coordinates.
  • screenY
    • long
    • The Y coordinate of the mouse pointer in global (screen) coordinates.
  • clientX
    • long
    • The X coordinate of the mouse pointer in local (DOM content) coordinates.
  • clientY
    • long
    • The Y coordinate of the mouse pointer in local (DOM content) coordinates.
  • button
    • unsigned short
    • The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
  • buttons
    • unsigned short
    • The buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, “Browser Back” button)=8, 5th button (typically, “Browser Forward” button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (= 1 + 2).
  • mozPressure
    • float
    • The amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
  • ctrlKey
    • boolean
    • true if the control key was down when the event was fired. false otherwise.
  • shiftKey
    • boolean
    • true if the shift key was down when the event was fired. false otherwise.
  • altKey
    • boolean
    • true if the alt key was down when the event was fired. false otherwise.
  • metaKey
    • boolean
    • true if the meta key was down when the event was fired. false otherwise.

an example

Continuing with our click events. Let’s build an example with three div areas, that are each clickable, and keep track of their own color progression.

To start with, if you look at the HTML file, you will see some basic styling for the three areas. Additionally, we have created three div containers in the HTML file. These divs will be the elements we play with in JavaScript.

Now, let’s turn our attention to the JavaScript code.

  • In line 2, we are selecting all three of the .container div elements.
  • In line 6, we are working through each of those elements using an ES6 for loop variant
  • In line 7, we are assigning a new listener, of type “click”, with the bgChange() function as the callback.
  • In line 10, we define the bgChange() function.
    • NOTE: we pass in a parameter called, event.
    • The event listener will pass this along to the function when it calls it by default. (hence why we do not pass it along in line 7.)
    • This event parameter will offer us access to the properties listed above.
  • In line 13, we use the event property currentTarget to get a reference to the element in question.
  • In line 18, we check if there is a property identified as idx on the element object.
    • By default, there will not be.
    • Since all elements are objects, we can add our own custom properties.
    • So, lets add a property called idx where we can store a reference to the index value of the background color for the specific element.
    • We create and initialize this value in the true function block of the conditional statement.
  • In line 22. we check if there is a property called flashing assigned to the element.
    • If there is not, this will return false. And we can move on.
    • If there, we have likely set it to be flashing, therefore, we can pass a reference to the setInterval function to the clearInterval function.
  • In line 28-36, we simply progress through one of three of the background colors, then update the idx property.
  • In line 41, we check if the event also included the pressing of the shift key.
    • This is capable through the events extra properties that were passed along.
    • If it did, then we will create a setInterval function, at 200ms.
    • Notice: that in this instance, we pass a reference the element we are working with. This only works since we created a return function within flashEl() that accepts this input parameter.
    • We also store a reference to this time, so that it can be stopped in line 24.

For more information on these properties of the click event, please visit the reference documentation on the Mozilla Developer Network.

The effect of all of this, is that each div element has its own color progression. By clicking on a div element, you can change its background color to one of three predetermined colors. More so, by using the shift key modifier, supplied to us by the event properties, when you Shift + Click a div element, it will flash, until you click it again without shift. This is accomplished with the timer functions.

[ Code Download ] [ View on GitHub ] [ Live Example ]

removeEventListener()

In addition to adding event listeners, developers can also choose to remove event listeners when necessary. This can be accomplished through the .removeEventListener() method.

To use this method, append it to the element that needs an event removed. Then pass to the method the type of event to remove, and the specific associated function to remove.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Other Event Listeners

There are many other event handlers you should learn about. Now that you have the basics of events down, I am going to ask you to study the following links to better understand what possibilities exist and how to use them.

keydown

The keydown event captures keystrokes.

In the case of some events, we want to capture them independent of sub-element. In this case, we can attach the listener to the document object.

For the associated function, we select a general div element created in the html document. Then we grab the key pressed, which is passed in via the event objects properties (i.e. event.key).

This can then be converted to an ASCII value, which can allow us to see if the key value is between A-Z or a-z. If it is, the letter is added to the current contents of the div element text.

If instead a space bar is pressed, the div elements text contents is deleted.

The script will effectively ignore any other key strokes.

To play with this example, click in the empty example window first. Then start typing.

[ Code Download ] [ View on GitHub ] [ Live Example ]

Other Specific Event Handlers To Be Aware Of

  • load
    • The load event is fired when a resource and its dependent resources have finished loading.
  • resize
    • The document view has been resized.
  • scroll
    • The document view or an element has been scrolled.
  • keydown
    • ANY key is pressed
  • keypress
    • ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continuously.)
  • keyup
    • ANY key is released
  • mouseenter
    • A pointing device is moved onto the element that has the listener attached.
  • mouseover
    • A pointing device is moved onto the element that has the listener attached or onto one of its children.
  • mousemove
    • A pointing device is moved over an element. (Fired continuously as the mouse moves.)
  • mousedown
    • A pointing device button is pressed on an element.
  • mouseup
    • A pointing device button is released over an element.
  • dblclick
    • A pointing device button is clicked twice on an element.
  • contextmenu
    • The right button of the mouse is clicked (before the context menu is displayed).
  • mouseleave
    • A pointing device is moved off the element that has the listener attached.
  • mouseout
    • A pointing device is moved off the element that has the listener attached or off one of its children.
  • select
  • Some text is being selected.
  • focus
    • An element has received focus.
  • blur
    • An element has lost focus.
  • dragstart
    • The user starts dragging an element or text selection.
  • drag
    • An element or text selection is being dragged (Fired continuously every 350ms).
  • dragend
    • A drag operation is being ended (by releasing a mouse button or hitting the escape key).
  • input
    • The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
  • CheckboxStateChange
    • The CheckboxStateChange event is executed when the state of a <checkbox> element has changed.
  • RadioStateChange
    • The RadioStateChange event is executed when the state of a <radio> element has changed.

All DOM Events can be studied from;

Further Reading

Please also read the following on events;


Previous section:
Next section: