JavaScript Events

Ronan McClorey
3 min readJul 10, 2020

--

While learning and writing in JavaScript one of feature that allowed you to do a lot and make your webpage interactive was adding event listeners. In JavaScript you can add event listeners anywhere on you page and have them follow through on a piece of code or call a function whenever the event takes place.

Photo by Markus Spiske on Unsplash

The event listener I used most and probably one of the most common was the “click” listener which can be placed on an element in the DOM and when that element is clicked the action within the listener is performed. Placing a click listener on page would look something like this:

This is a basic example and when the node with the specific class name gets clicked the console will log “I have been clicked”. Obviously there is better more practical uses that logging something to the console. For example placing a click listener on a like button that updates the likes on Facebook or Instagram Post. There are a lot of different event listeners built into JavaScript and so far in my learning I have only used a handful of them. I used the click listener here as the first example because I can see how practical it is and can see examples of how it would be put to use or work on my different web pages.

Another event listener I have used and found can be useful in making an application more interactive is “mouseenter” and “mouseleave”. Mouseenter works by running the code in the listener (example: changing the background color) when the mouse moves over an element that the listener is placed on. Mouseenter doesn’t necessarily have to have a mouseleave listener however when the mouse moves off an element it won’t change back to what it was originally without a mouseleave running code telling it to. Therefore, it depends on your application of mouseenter but, in a lot of cases it would be useful to have a mouseleave go with a mouse enter to return the element to its original state.

Event listeners also aren’t limited to action of the mouse or clicks. Event listeners can be placed on the keyboard too to produce an action when a key is pushed with the “keydown” event listener.

document.addEventListener("keydown", function(e){if (e.key === "a"){
console.log("a")
}
if (e.key === "ArrowUp"){
console.log("up")
}

Each key has its own value and when pressed it will run through whatever code placed inside of it is asking. Again this is a basic not practical example just console logging the key that was pressed. However, when testing out new code or something I haven’t used before I often use console.log to insure it is working as I expected. There are useful and practical use cases for this we could use the arrow keys in an application to move an element around.

Photo by Dries Augustyns on Unsplash

There are a lot more event listeners than the ones I’ve mentioned here, these are just a few I have used thus far.

--

--

No responses yet