onInput Event

By  on  

Coding HTML forms has been painful my entire career. Form controls look different between operating systems and browsers, coding client side and server side validation is a nightmare, and inevitably you forget something somewhere along the line. Some behaviors don't act the way you'd hope, like onChange, which only fires when the user leaves (blurs) a given form controls. Enter the onInputevent, which changes upon keystroke, paste, etc.

// Try it here:  https://codepen.io/darkwing/pen/KKmBNvg
myInput.addEventListener('input', e => {
  console.log(e.target.value);
});

These days it seems like the old onChange behavior isn't useful -- we always want to react to any user input. onInput also fires on elements with contenteditable and designmode attributes. Most modern JavaScript libraries like React treat onChange like onInput, so it's as though onChange has lost its use!

Recent Features

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

Incredible Demos

  • By
    Facebook Sliders With Mootools and CSS

    One of the great parts of being a developer that uses Facebook is that I can get some great ideas for progressive website enhancement. Facebook incorporates many advanced JavaScript and AJAX features: photo loads by left and right arrow, dropdown menus, modal windows, and...

  • By
    Firefox Marketplace Animated Buttons

    The Firefox Marketplace is an incredibly attractive, easy to use hub that promises to make finding and promoting awesome HTML5-powered web applications easy and convenient. While I don't work directly on the Marketplace, I am privy to the codebase (and so...

Discussion

  1. Thomas

    I agree that onInput is very handy, but I beg to differ on the point that there is no more use for onChange. E.g. in this tutorial for creating a custom audio player: https://css-tricks.com/lets-create-a-custom-audio-player/#play-pause There, the onChange event is used for a range input element to seek to a passage in an audio file. While playing the audio, you might not want the current position in the audio to change on every input, but only after having finished seeking the correct passage.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!