DOM Events:
element.getEventListener("event", function(parameter));
element.getEventListener("event", function);
element.getEventListener("event", function(parameter), useCapture);
element.removeEventListener("event", function)
DOMContentLoaded
Just as every cause has an effect, so in JavaScript
for something to happen, we need to call for it. We have been doing this
so far using either self-declaring functions
or using the on
method in the DOM.
But, we can also tell the code to listen for an event. We did this here, for example.
On this page, we have again the light and dark theme buttons. But look at the addition to the code in the function timeDarkTheme()
. We have added the possibility
of pressing certain keys to change the theme from light to dark:
Or press "l" for the light theme, or "d" for the dark theme.
It is also possible to achieve the same effect by calling an external function from our getEventListener
. But when we do, we include neither the ()
not its parameter
. These are included in the function itslef that we call:
Press "b" for dark theme or "w" for light theme.
useCapture
is a Boolean
. It is set to either true
or false
within the declaration.
It is used to define whether the event listener is triggered on the element itself, or its parent element(s), or on event capturing
or bubbling
: see here for explanantion and
here for example.
Removes an event listener. For example, use it with a button. Must call an outside function.
Mouse over the green box below. Then click the button below.
As I've been writing this website, I've had numerous instances where an alert has triggered BEFORE the page has loaded. Because JavaSript
can modify code, this is
bad practice. To stop this from happeneing, use the DOMContentLoaded
event.
This has to be triggered before the page loads, in order to tell the code to load completely before triggereing the alert (or whatever).
Because of this, the associated <script>
has to be placed within the <head>
element of the HTML.
Also, its associated function has to be included within the <script>
's code.
To rectify this, I have told the script to load after the page does, and also to put a small delay before the script exaecutes: