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.
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=
attributeThe 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 ] |
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 ] |
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;
click
, focus
, mouseover
).
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 ] |
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
type
bubbles
cancelable
view
detail
currentTarget
relatedTarget
screenX
screenY
clientX
clientY
button
buttons
mozPressure
ctrlKey
shiftKey
altKey
metaKey
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.
.container
div elements.bgChange()
function as the callback.bgChange()
function.
event
.event
parameter will offer us access to the properties listed above.currentTarget
to get a reference to the element in question.idx
on the element object.
idx
where we can store a reference to the index value of the background color for the specific element.true
function block of the conditional statement.flashing
assigned to the element.
setInterval
function to the clearInterval
function.idx
property.shift key
.
flashEl()
that accepts this input parameter.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 ] |
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.
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
All DOM Events can be studied from;
Please also read the following on events;