Monkey Raptor

Friday, January 23, 2015

JavaScript: Using HTML5 Input Event

The input event can be used to detect any change on input or textarea. It's fired right away, unlike the change event.
This event is great for capturing:
  • Keypress (keydown/keyup) from the keyboard.
  • Mouse right click ► paste/cut.
  • Paste/cut via the keyboard.
So it's like all keypress (keyup and keydown), change, focus, contextmenu, etc. swiftly combined.

We can use the on method or the newer addEventListener for that particular event.

This demo looks like Bing Translator or Google Translate input behavior.
But it's different method there. Maybe.

Let's take a look at the demo below.
DEMO
Paste/cut/type any text on each
If you type just [space] it'll show the whitespace. I didn't put something for that.
[input] element output
[textarea] element output



This is the HTML elements stacking


Then, the CSS (styling)


The last, the JavaScript


Inline trigger
When using the on method, the trigger can be placed inline within the element, such as:
<input type="text" oninput="the_handler()" placeholder="...**>
Then we need to declare the defined the_handler() function above.

Switching to addEventListener
As I mentioned above, we can also use addEventListener to capture the event.
Look at the example below.

From this:
element.oninput = function() { /*the_handler_function*/ };
Switch the method to this:
element.addEventListener("input", function() {
  /*the_handler_function*/
}, false);


Internet Explorer 9 and up support this HTML5 input event. And of course, Chrome, Firefox, Opera, Maxthon, Yandex, etc.


References
  1. HTML5 input event documentation at Mozilla Developers Network
  2. HTML5 input event documentation at IE Dev Center
JavaScript: Using HTML5 Input Event
https://monkeyraptor.johanpaul.net/2015/01/javascript-using-html5-input-event.html

No comments

Post a Comment

Tell me what you think...