Friday, June 17, 2022

Hack 7. Know What’s Going On in Your App with New DOM Events


HTML5 provides a slew of new events for you to latch on to. The world has moved beyond mouse clicks and keyboards. Now the Web has, too.

DOM events haven’t changed much in the past 15 years. I think the last new DOM event we got was the mouse scroll (that’s what you call that little spinner in the center of your mouse). Even touch events are not officially supported DOM events, although they are much more prevalent (and supported) than DOMMouseScroll.

With HTML5 we have tons of new input types to work with. As JavaScript is an event-driven language, it helps to work with a DOM that also natively fires events when actions take place. Some of these actions are directly related to a user interaction (such as the traditional DOM events), whereas others are related to events triggered by the user agent (such as going offline and coming back online). Let’s start with a look at some form events.

The oninput, onchange, and oninvalid Events

In the past we have relied on keydown and keyup events quite often to determine what’s going on within form elements. The bad thing about key events is that they don’t specifically apply to the input element itself, as technically it’s the document, not the input, which is receiving the keystrokes. This led us to trick the DOM, by temporarily adding key events after an input receives focus and removing the key listeners once the blur event of an input is fired. This has been terribly inefficient.

With the oninput event, a listener can be placed directly on an input tag (or bubbled up from one) and be associated with the actions of that input only. Let’s look at a traditional listener with an oninput event instead of an onkeypress event:

<input id="myInput" type="text" placeholder="enter text">

<script>

document.getElementById('myInput').addEventListener('input',function(e){
 console.log("I just changed an input on:", e.target);
}, false);

</script>

Once you begin typing in the input field, the log will be fired. As you can see, the input event is attached to the myInput field, so input into any other input field will not trigger this event.

Similarly, we have two additional events that can be attached to the input field: onchange and oninvalid. The onchange event fires once the value attribute is updated. You may not immediately see the need for an onchange event, since we do have oninput and numerous other events that can be triggered on an input change. But let’s think about some of the new HTML5 elements, such as the input with type set to range. The range input or slider has no input mechanism; it simply changes. When I drag the handle from one position to another it doesn’t fire an oninput event, only an onchange event. Similar events are required for other input mechanisms, such as date pickers, number wheels, and color pickers. These new input types make the onchange event not just handy, but essential.

The oninvalid event is a similar new event that is fired when a form element is deemed invalid. Unlike many of our other validity checks, current implementations do not work on the form element itself, but rather on the individual inputs. Remember a few hacks back when I was complaining about how the form elements weren’t validated in real time (such as when you enter data into the input rather than at form submit) and that only the CSS state change was in real time? Let’s look at an example of how we can put some of these events together to make the solution to my pet peeve a reality!

Real-Time Form Validation with the oninput/oninvalid Events

In order to validate an input field while the user is entering data into it, we need an event which fires as the user changes the value of the input. In the past we would have to follow troublesome keystrokes, but with the oninput event we can easily attach a listener to the input in question, and react to the change.

Once we catch that event we need to do some ad hoc validation checking, so for this we will go back to the checkValidity() method (see [Hack #6]) to get the input to self-validate. This can easily be fired from the oninput event. At this point, if the input is deemed invalid the oninvalid event will be fired alongside it.

The last thing we need to do is to attach an event listener to the oninvalid event, and have it fire a function that will indicate to the user that the value she entered is invalid. We’ll follow this up with some CSS to reinforce the state of the input.

Let’s take a look at the code:

<!DOCTYPE html>
<html>
<body>

<style>
input[type=number]{border: 2px solid green}
input:invalid {border: 2px solid red}
</style>

<form name="myForm">
  Pick a number, any number between 1 and 5:
  <input type="number" name="quantity" min="1" max="5" /> <br />
  <input type="submit" name="mySubmit" />
</form>

<script>
document.myForm.quantity.addEventListener('input', function(e){
                                           this.checkValidity()
                                                   }, false);

document.myForm.quantity.addEventListener('invalid', function(e){
alert('Your Number needs to be between 1 and five, you chose '+this.value
+'.')
}, false);
</script>

</body>
</html>

Endless fun, right? We now have the best of both worlds: built-in validation with real-time responsiveness.

Other New Events

While we are on the subject of events, HTML5 is proposing the adoption of a slew of new events similar to the ones mentioned in the preceding section. Most of these events focus on a user action, and they fire before, after, and during the event. Here’s a list of events that had not been adopted at the time of this writing, but are likely forthcoming:

onabort

oncanplay

oncanplaythrough

onchange

onclick

oncontextmenu

oncuechange

ondblclick

ondrag

ondragend

ondragenter

ondragleave

ondragover

ondragstart

ondrop

ondurationchange

onemptied

onended

oninput

oninvalid

onkeydown

onkeypress

onkeyup

onloadeddata

onloadedmetadata

onloadstart

onmousedown

onmousemove

onmouseout

onmouseover

onmouseup

onmousewheel

onpause

onplay

onplaying

onprogress

onratechange

onreadystatechange

onreset

onseeked

onseeking

onselect

onshow

onstalled

onsubmit

onsuspend

ontimeupdate

onvolumechange

onwaiting

 



SHARE THIS

Author:

urdufundastory.blogspot.com is the first of its kind of trendsetting venture existent in Pakistan. It is for the first time in the history of this nation that a large scale project of such nature, evolved from an extraordinarily revolutionizing concept to a practical fulfillment.

0 Comments: