Member-only story
JavaScript Events Handlers— onfocus
, oncancel
, and oncanplay
In JavaScript, events are actions that happen in an app. They’re triggered by various things like inputs being entered, forms being submitted, and changes in an element like resizing, or errors that happen when an app is running, etc. We can assign event handler to handle these events. Events that happen to DOM elements can be handled by assigning an event handler to properties of the DOM object for the corresponding events. In this article, we will look at the onfocus
, oncancel
, and oncanplay
event handlers.
onfocus
The onfocus
property of the document
object lets us set an event handler for the focus
event, which is the opposite of the blur
event. The focus
event is trigger when a user sets focus on an HTML element. If we want to the focus event to fire for non-input elements, we have to put tabindex
attribute to it. What that attribute added we can focus on it with our computer’s Tab key. For example, we can attach the onfocus
event handler to the document
object by writing:
document.onfocus = () => {
console.log('focus');
}
We can also get the Event
object that triggered the focus event by adding the event
parameter to the event handler function like in the following code:
document.onfocus = (event) => {
console.log(event);
}