An Intro to Javascript & Event Listeners

Javascript, HTML, & CSS Relationship

Javascript allows for the addition of interactive and dynamic functionality on a webpage through. This is done through event handling, and event listeners. Before diving into event listeners, it is to ground ourselves in the relationship between HTML, CSS and Javascript, and how this serves as an important foundation for how event listeners operate.

  • 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.
  • The JavaScript file works to determine the interactions of the elements on the page. This can be triggered by listening to events (why this part is important) that can include clicking, key presses, hovering or other types of actions that the browser can listen for. Javascript is what gives functionality to the webpage.

Event Listeners

Event listeners are features and functionality in Javascript that are occurrences that “fires” off in your code when initiated by some signal. As mentioned above in the relationships with CSS and HTML, Javascript allows for functionality, and event listeners. The Mozilla Developer Network (MDN) has a great resource of common event occurrences, link here.

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!

  • 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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store