A quick breakdown of relationship can be seen as:
- The HTML file acts as the structure of the webpage. Many times, HTML is compared to a frame and foundation of a building.
- The CSS file works to style the page. This can include features such as changing positioning of elements, colors, size, and more.
In our course, we have used “click” as one of the most common event occurrences that listens for mouse click on a specific element.
Syntax for Event Listeners
The syntax for adding an event listener is by using the addEventListener() method to a specific HTML element. This can be done in several ways. You can be done by identifying and creating a variable for a specific HTML element, and then appending the .addEventListeners(). Word of advice, make sure the syntax follows camel case —this can be tricky!
const element = document.getElementById(“button”) element.addEventListener(“click”, sayHi);
Breaking down the code above:
- Created a function called SayHi, which console.logs the string “Hi”
- We created a variable called “element”, that would store the element that was selected on the document called “button”.
- Adding the .addEventListener() function, with the parameters of event — in this “click”, and the second parameter being the function — in this case the sayHi function that was defined before. There is also a third parameter for useCapture, but for the scope of this post we will only use the first two.
So at this point, we created a function that will console.log a message, and we have create an element variable. What we want to do is tie these two pieces of code together, so that when the element of button is clicked, it will console.log the message “Hi” to the console.
This is where we introduce the .addEventListener function. We add the function to the specific element variable, so that the Add Event function is called upon that specific element we defined prior. The first parameter, we are going to use the keyword “click” which is a reserved string that points to the click action. Refer back to the MDN Event Reference List for more events! Next, the second parameter is the function we defined prior. For this part, we can actually define a function in line, but for the scope of this post we had a prior function we called back upon.
The final result of this code would be combining the 3 components, by clicking on the element variable with the id of button, the event listener will “listen” to the click event and fire off the function of sayHi, posting “sayHi” onto the console!
Event Listeners are a great way to add fun functionality to your webpages, and it is no surprise on why it is used by so many websites. My advice for some further reading would be to check out these links below: