Categories
JavaScript

JavaScript Events Handlers- onfocus , oncancel and More

Spread the love

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 oncanplaythrough , onchange , onclick , and onclose event handlers.

oncanplaythrough

The oncanplaythrough property let us assign our own event handler function to it to handle the canplaythrough event. This event is triggered when the user agent can play the media and estimates that there’s enough data loaded to play the media all the way to the end without having to stop and buffer for more data. For example, we can listen to the canplaythrough event for a video by adding the following HTML code:

<video width="320" height="240" controls id='video'>  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">  
</video>

Then in our JavaScript code we can add:

const video = document.getElementById('video');  
video.oncanplaythrough = (event) => {  
  console.log(event);  
}

We can also attach the canplaythrough event listener by using the addEventListener method on the video DOM node instead like in the following code:

const video = document.getElementById('video');  
video.addEventListener('canplaythrough', (event) => {  
  console.log(event);  
});

Either way, we can check if enough parts of the media has been downloaded in order for it to finish by using the readyState property of the media element, which include video and audio elements. The readyState can have one of the following possible values:

  • The constant HAVE_NOTHING or number 0 — there’s no information about the media resource
  • The constant HAVE_METADATA or number 1 — enough parts of the media resource has been downloaded that the metadata attributes are initialized. Seeking won’t raise exceptions in this state or beyond
  • The constant HAVE_CURRENT_DATA or number 2 — there’s enough data available for current playback position, but not enough to actually play more than one frame
  • The constant HAVE_FUTURE_DATA or number 3 — there’s enough data for the current playback position is downloaded, as well as enough data for playing at least a little bit into the future, which means at least 2 frames of video.
  • The constant HAVE_ENOUGH_DATA or number 4 — there’s enough data available, and that the download rate is high enough, that the media can be played through to the end without interruption.

We can get the readyState property of our video element by writing the following code:

const video = document.getElementById('video');  
video.oncanplaythrough = (event) => {  
  console.log(event.target.readyState);  
}

If our video can be played all the way through, we should have 4 logged in the console.log output.

onchange

The onchange property let us assign an event handler to it to handle the change event. The change event is triggered when the user commits a value change to a form control. This may be done by clicking outside of the control or by using the Tab key to switch a different control. For example, we can use it to get the input value of an input element after a user has enter a value to the input and then move the focus outside the input. First we can add the following HTML code:

<input type="text" size="50" id='input' placeholder='Input'>

Then in the JavaScript code, we add:

const input = document.getElementById('input');  
input.onchange = (event) => {  
  console.log(event.target.value);  
}

The value property of the input element will have the text value that we entered into the input element that we added to the HTML code. It’s very helpful for getting the input as the user types and moves between different inputs and moving between different parts of the form.

onclick

We can assign an event handler to the onclick property of an element to do something when the user clicks on an element. The click event is handled by the onclick event handler, which is trigger when the user clicks on the element. It fires after the mousedown and the mouseup event in that order. The click event doesn’t get triggered on non-mouse or touch screen devices. To accommodate these users, we can handle the keydown event. For example, we can use it to get the position of the browser tab that was clicked with the following HTML code:

<p>Click anywhere in this example.</p>  
<div id='message'></div>

We will add the message for tracking the position the mouse is in in the div element.

Then in our JavaScript code, we can write:

const message = document.getElementById('message');  
document.onclick = (event) => {  
  message.innerHTML = `You click coordinate is x = ${event.clientX}, y = ${event.clientY}`;  
}

In the code above, we got the position of the page the mouse was in the when the mouse was clicked on the page. We can use the Event object’s clientX and clientY to get the x and y coordinates of each mouse click respectively. Then when we run the code, then we can see the mouse coordinate wherever the mouse was clicked.

onclose

To get handle the situation when the dialog element has closed, we can use the onclose event handler, since the close event is triggered when it’s closed. Handling the event with the onclose event handler prevents it from bubbling, so parent handlers aren’t notified of the event. Only one onclose handler can be assigned to an object at once. However, if we use the addEventListener to attach the event handler function to our element, then we can get around this limitation. The difference between the close and cancel events is that the close event is triggered no matter which way the dialog box is closed. For example, we can use it like in the following code:

const dialog = document.getElementById('dialog');  
const openButton = document.getElementById('open-button');  
openButton.onclick = () => {  
  dialog.showModal();  
};

dialog.onclose = (event) => {  
  console.log('dialog closed');  
  console.log(event);  
}

Then we have to add the dialog element to our HTML code:

<button id='open-button'>  
  Open Dialog  
</button>  
<dialog id="dialog">  
  <form method="dialog">  
    <p>  
      Dialog  
    </p>  
    <menu>  
      <button id="cancel-button" value="cancel">Cancel</button>  
      <button id="confirmBtn" value="default">Confirm</button>  
    </menu>  
  </form>  
</dialog>

In the code above we added a dialog element to the HTML and get the DOM element for the HTML dialog element with the getElementById method, which gets us has the following methods:

  • close() — a dialog instance method to close the dialog element. An optional string can be passed in as an argument, which updates the returnValue of the dialog , which is useful for indicating which button the user used to closed it.
  • show() — a dialog instance method to display the dialog modelessly, which means we still allow interaction from the outside. It takes no arguments.
  • showModal() — a dialog instance method to display the dialog as a modal over the top of anything else. It displays on the top layer along with a ::backdrop pseudo-element. Interaction with elements outside the dialog is blocked and the content outside can’t be interacted with.

dialog DOM elements also have the following value properties:

  • open — a boolean property that reflects the open HTML attribute, which indicates whether a dialog is open for interaction.
  • returnValue — a string property that sets and returns the return value for the dialog. We can assign it a value directly or we can pass in an argument to the close method to set this property.

We didn’t need to call the close() method to close the dialog box. Having a button is enough. Also, we don’t have to click a button to close the dialog, we can also press the Esc key on our keyboard to do so.

Note that the dialog element isn’t enabled by default on Firefox. To use it in Firefox, we have to set dom.dialog_element.enabled to true in the about:config page. Chrome has this feature enabled by default. Then if we click the ‘Open Dialog’ button that we just made, then we will see a native browser dialog box. Then if we press the Esc key to close the dialog, then the cancel event will be triggered and the event handler function that we assigned to the dialog.oncancel will run. The event parameter of the event handler function will get an Event object, which has the information about the source of the cancel event which is our dialog element. So we would get something like the following in our console.log output:

bubbles: false  
cancelBubble: false  
cancelable: false  
composed: false  
currentTarget: null  
defaultPrevented: false  
eventPhase: 0  
isTrusted: true  
path: (5) [dialog#dialog, body, html, document, Window]  
returnValue: true  
srcElement: dialog#dialog  
target: dialog#dialog  
timeStamp: 3902.0349998027086  
type: "close"

The oncanplaythrough property let us assign our own event handler function to it to handle the canplaythrough event. The canplaythrough event is trigger when the media is complete downloaded so that the browser won’t have to stop and buffer to play the media all the way through. The onchange property let us assign an event handler to it to handle the change event. The change event is triggered when the user commits a value change to a form control. We can assign an event handler to the onclick property of an element to do something when the user clicks on an element. To get handle the situation when the dialog element has closed, we can use the onclose event handler, since the close event is triggered when it’s closed. The close event is different from the cancel event in that the cancel event is only trigger when the Esc key is pressed to close the dialog, but the close event is triggered whatever way the user used to close the dialog.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.