The previous JavaScript posts have all been really simple — it is time to try something slightly more advanced. In this example, I have used the <dl>
tag with its children, <dt>
and <dd>
to create a list of terms and their corresponding definitions.
Knowledge required:
1. Syntax
The addEventListener()
method attaches an event handler to a DOM element.
element.addEventListener(event, function, useCapture)
element
- The DOM element being monitored.
event
- The event that is being listened for, for example, click (a mouse click).
- Required.
function
- The function to be returned when the event has occurs.
- Required.
useCapture
- false – The handler is executed in the bubbling phase.
- true – The handler is executed in the capturing phase.
- Optional
2. Example 1
2.1 Targeting
First, we use getElementByID()
to identify a specific HTML element by its id
so that we can “listen” to it, by which we mean to wait for it to do something — or have something done to it. The element we want to watch is the <button>
.
2.2 Listening
Then we add a listener to the <button>
element above so that when a specific event happens to that element, we can do something. In this case, the specific event we are listening for is the click
event on the button that has the id revealer
. The name of the event listener and the event match: the click
event listener listens for the onclick
event.
2.3 Selecting
We are going to do something to all the <dd>
elements in the HTML. We use the querySelectorAll()
method to select all <dd>
elements in the HTML document.
2.4 Looping
Finally, we loop through all the <dd>
‘s in the document by iterating through the array returned by the querySelectorAll()
method thereby changing the display
attribute of all the <dd>
s to make them visible. The for loop
is a programming pattern that you will encounter in almost all languages.
See the Pen Javascript addEventListener() method by David Fox (@foxbeefly) on CodePen.
3. Bubbling
coming soon…
4. Example 2
coming soon…
References:
- W3Schools.com. (no date) HTML DOM Element addEventListener(). Available at: https://www.w3schools.com/jsref/met_element_addeventlistener.asp (Accessed: 29 June 2024).