May 23, 2021
let myButton = document.getElementById("myButton");
let sayHai = function(e) {
console.log("hai");
}.AddEventListener('click', sayHai); myButton
Here are a couple commonly used events:
click
: When a user clicks the elementload
: When the object has finished loadingmouseover
: When the mouse hovers over the elementinput
: When the contents of an input element is changed (ie: a checkbox is clicked or text is changed)For all event types, see the documentation
Use the addEventListener
method of html elements
For example:
let myDiv = document.querySelector('#myDiv');
.addEventListener('load', myFunct); myDiv
Use the removeEventListener
method of html elements
For example:
let myDiv = document.querySelector('#myDiv');
.removeEventListener('load', myFunct); myDiv
target
: The HTML element object that this event happened fortype
: What kind of event happenedtimestamp
: When the event happenedGoing back the first example:
let myButton = document.getElementById("myButton");
let sayHai = function(e) {
console.log("hai");
}.AddEventListener('click', sayHai); myButton
We can if we add an argument to our function, the first arguement (usually called 'e') will be passed the event object
let myButton = document.getElementById("myButton");
let sayHai = function(myEventObject) {
console.log("hai");
console.log($`Event Object: {myEventObject}`);
}.AddEventListener('click', sayHai); myButton