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

Incredible Demos

  • By
    Send Email Notifications for Broken Images Using jQuery AJAX

    It's usually best to repair broken image paths as soon as possible because they can damage a website's credibility. And even worse is having a user tell you about it. Using jQuery and PHP, you can have your page automatically notify you of broken...

  • By
    MooTools Window Object Dumping

    Ever want to see all of the information stored within the window property of your browser? Here's your chance. The XHTML We need a wrapper DIV that we'll consider a console. The CSS I like making this look like a command-line console. The MooTools JavaScript Depending on what you have loaded...

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!