JavaScript interaction with HTML is handled through events. Events happen when either the user or the browser manipulates the page in some way. We can use these events to do whatever our imagination allows, from sending alerts, validating data, or perhaps shooting fireworks from our webpage.
In this post, we’re going to talk about some common events that occur with websites, but first…
Some notes on Event Listeners
An event kicks off whenever an action occurs on a page that JavaScript can react to, such as when a user clicks on a button (click event) or presses a key (keypress event).
When we attach an event listener to an HTML element, the element now has the ability to “listen” for a given event to fire.
Say for example we want the text color of an <li> element to change and shoot fireworks when the user clicks on it. We could use the following code:
liElement.addEventListener('click', function(e){
e.target.style.color = "red"
//DO IT NOW
shootFireWorks()
})
In the code above, we’ve attached an event listener to our <li> element with a first argument ‘click’, and a callback function for the second argument. We’ve now given the element the ability to “listen” for a click, and then it’ll do whatever is in the callback function.
Some common events
Mouse events
I think it’s easy to say that because we use the mouse to interact with web pages, mouse events are one of the most frequently used events (side note: there are some additional events used for touch-enabled devices). Some examples include:
- click Event: Occurs when a mouse button is pressed and released on an element
- dbclick event: Occurs when a mouse button is clicked on twice
- mouseenter event: Occurs when the mouse pointer enters an element
- mouseover event: similar to mouseenter, but in addition to the parent, the event occurs when the pointer enters one of its children
- and so much more…
Form and focus events
The submit
and reset
events fall under form events. Like their names suggest, the form events fire when buttons of a specific type within a form are clicked on. Focus events occur when an element receives…well, focus.
Think of all the times you’ve filled out a form on the web and when you click in an input field to type in a password, a small effect like a border highlight or background color change occurs. Those effects happen in a callback function when the focus event occurs.
Keyboard events
Keyboard events check for when there’s a usage of a keyboard key press. The events include:
- keydown event: occurs once when a key is pressed.
- keyup event: occurs once when a key is released.
- keypress event: occurs continuously while a key is pressed. (It’s deprecated and recommended that it’s not used anymore)
The difference between keydown and keypress is that keydown acknowledges all keys when they’re pressed, but keypress will not acknowledge keys that do not produce a character, like Alt or shift.
So there you have it! Some common JavaScript events. Happy coding!