DOM objects, in addition to being rendened by the browser, can also respond to user actions such as mouse clicks and key strokes.
An event is anything that happens independent of what the code is otherwise doing.
Usually this is when something outside the program such as the user clicking the mouse or typing a key.
When an event occurs the browser creates an object with relevant information to represent the event.
For instance, an event representing a mouse click would include information such as the position on the screen where the click happened, whether there were any shift or control keys held down at the time, and what element was clicked.
Event handlers are just functions that are called by the browser when events occur.
As you should recall from last semester, we normally define a function by assigning a function value to a variable:
const foo = (e) => {
// do something
};
The variable is foo
and the function is everything to the right of the =
.
Change the place we assign the function value to a property of an element.
// Get an object representing the first paragraph
// in the document
const paragraph = document.querySelector('p');
paragraph.onclick = (e) => {
// do something
};
This assigns the function value to the onlcick
property of the paragraph element.
If that property is set, the browser will call that function when the paragraph is clicked.
const paragraph = document.querySelector('p');
const foo = (e) => {
// do something
};
paragraph.onclick = foo; // N.B. *not* foo()
Note: we are assigning the value of the function, not calling the function, i.e. foo
not foo()
.
In the previous slides we used document.querySelector
to get an object representing an existing element in the page.
This could be an element that was in the original HTML or an element that was previously added to the document.
When we create objects dynamically with document.createElement
we can attach event handlers to them before or after we add them to the page.
const paragraph = document.createElement('p');
paragraph.append(document.createTextNode('Click me!');
paragraph.onclick = (e) => {
console.log(e);
};
document.body.append(paragraph);
This code will add a new paragraph to the document that, when clicked, logs something to the Javascript console.
If you haven't yet, in your Codespace make a new project from the web-demos
kit.
./start-project my-web-demos web-demos
Take a look at the code of the different demos and see how they use event handlers. Then come up with some changes you'd like to make and try to make them.