Applying Callbacks with addEventListener
An event handler is a function that is run when some pre-defined "event" occurs in the browser. Try to make the following work in the dev console while inspecting your Portfolio Project:
We’ve explored how we can use the document object (an API for interacting with the DOM) with querySelector() to ‘grab’ Element objects from the DOM.
Once we have that, we can apply addEventListener
, passing in a string that describes the Event (e.g. 'submit' or 'click') as the first argument and a callback function as the 2nd argument.
function sayHey() {
console.log("heeey");
}
// Alternately, we can ask the browser to run it at a later time
// The below is called an event handler, take a guess at what it does...
// Add it to an HTML document containing a div#target and test it out
document.querySelector("h1").addEventListener("click", sayHey);
// Often times, instead of using a variable, we'll just define the function inline
document
.querySelector("h1")
.addEventListener("click", function saySameDeal() {
console.log("same deal");
});
When a function is used as a callback, it's often written inline as in the example above. These function traditionally don't have names of their own, and are instead referred to as anonymous functions.
This callback function in turn pass an argument that ‘captures’ the actual event object, that has properties and methods such as preventDefault() which will prevent the browser from trying to submit the , as is the browser’s default behavior. https://codepen.io/codefinity/pen/ExYOvJQ
Arrow Functions
JavaScript has given us a new syntax for anonymous functions called "arrow" syntax. It looks like this:
// original syntax
document.querySelector("div").addEventListener("click", function logOnClick() {
console.log("A div has been clicked!");
});
// arrow function
document
.querySelector("div")
.addEventListener("click", () => console.log("A div has been clicked"));
As you can see, it saves us some keystrokes, which is generally a good thing. There is one specific caveat when using this syntax that we will probably run into later.
Last updated
Was this helpful?