html5 - Javascript keypress event and e.keycode -
html5 - Javascript keypress event and e.keycode -
i have code suppose update number of remaining characters left when user types in text input
. code triggered using keypress
event. problem code triggered after 2 keypress
. why happen?
i have code show key of ascii code character shows 8 , shows when press backspace. , how utilize string.fromcharcode(event.keycode} ;
method.
why event
parameter added function
? how e.keycode
know displaying keycode
of user's input.
code sample
html
<div id="page"> <h1>list king</h1> <form id="messageform"> <h2>my profile</h2> <textarea id="message"></textarea> <div id="charactersleft">180 characters</div> <div id="lastkey"></div> </form> </div>
javascript
var el; // declare variables function charcount(e) { // declare function var textentered, chardisplay, counter, lastkey; // declare variables textentered = document.getelementbyid('message').value; // user's text chardisplay = document.getelementbyid('charactersleft'); // counter element counter = (180 - (textentered.length)); // num of chars left chardisplay.textcontent = counter; // show chars left lastkey = document.getelementbyid('lastkey'); // lastly key used lastkey.textcontent = 'last key in ascii code: ' + e.keycode; // create msg } el = document.getelementbyid('message'); // msg element el.addeventlistener('keypress', charcount, false); // keypress -call charcount()
the keypress
event triggered before input's value updated, why counter not date. i'd suggest hear input
event if don't need keycode. can hear keyup
(but update won't straight forward) or combination of keypress
, keyup
(from "how text of input text box during onkeypress?", updated right answer's fiddle). actually, keypress
event doesn't seem triggered when press backspace. been said, other solution ignore "muted" keys ("backspace", "shift", "command" , on) hear "input" event (but won't have access event.keycode
). otherwise can ignore code when keycode not relevant. in regard string.fromcharcode, utilize string.fromcharcode(event.keycode)
keycode's "human" equivalent. the event passed function object containing informations given event, including pressed key.
javascript html5 javascript-events keypress keycode
Comments
Post a Comment