08 Handout 1
08 Handout 1
SoloLearn
JS can contain code that is executed whenever an event occurs, such as when a user clicks
on an HTML element, moves the mouse, etc.
When an event occurs on a target element, an event handler function is executed.
A. Handling Events in JS
1. A user initiates an action on a JS-enabled web page or application
2. The element that was interacting with the user calls on event handlers assigned to them;
they can either be directly written as an attribute of its corresponding HTML element
or assigned using the ID value for the getElementById() method of the document
object.
3. The event handlers then execute any code that will accomplish any specific task
associated to the element that the user interacted with.
B. JS Event Attributes
There are three (3) JS event attributes that are commonly used to call corresponding
event handlers:
o The onload and onunload attributes are triggered when the user enters or leaves a
page; these are usually found within the <BODY> element of a web page. The
window.onload attribute can also be used to run code AFTER the web page has
been completely loaded.
o The onchange attribute is mostly used in HTML textbox controls. The event handler
gets called when the text inside the textbox changes and focus is lost from the
element.
C. JS Event Listeners
JS uses the methods addEventListener() and removeEventListener() to attach and
detach event handlers to elements without overwriting already existing event handlers.
These methods mostly contain three (3) parameters, each being separated by commas
(,):
o The first parameter is the event type (for example, “click” for a mouse click, or
“mousedown” for a drag-and-click).
o The second parameter is the event handler function that will be called when the
specified event type occurs.
o The third parameter is an optional Boolean value parameter specifying whether to
use bubbling (running event handlers from the element up to its parent elements) or
capturing (running event handlers from the element’s parent elements down to the
element itself).
Programmers can assign as many event handling methods as they need to a single
element (for example, one method for clicks, one methods for double-clicks, etc.).
Max Chadwick
It is the definition of the element order followed by an event handler whenever an event
occurs.
Elements in web pages are hierarchical in nature, with elements written within other
elements.
The element order is usually defined in the DOM.
References:
SoloLearn (n.d.). JavaScript Tutorial. Retrieved on April 17, 2018 from
https://www.sololearn.com/Course/JavaScript/
SoloLearn (n.d.). jQuery Tutorial. Retrieved on April 17, 2018 from
https://www.sololearn.com/Course/jQuery/
Chadwick, M. (2017). Overriding inline onclick attributes with event capturing. Retrieved
on July 5, 2018 from https://maxchadwick.xyz/blog/overriding-inline-onclick-with-event-
capturing