jquery - Simplest way to detect keypresses in javascript -
i have idea game in javascript (i'm going make easeljs) , i'll have detect keypresses. after looking around on internet i've seen lot of suggestions (use window.onkeypress, use jquery, etc.) every option there's counterargument. guys suggest? using jquery sounds easy enough have virtually no experience library (and i'm not particulary veteran @ javascript either) i'd rather avoid it. if jquery best option, can give example (with explanation awesome) of how this?
i guess gets asked lot couldn't find clear answers. in advance!
with plain javascript, simplest is:
document.onkeypress = function (e) { e = e || window.event; // use e.keycode }; but this, can bind 1 handler event.
in addition, use following able potentially bind multiple handlers same event:
addevent(document, "keypress", function (e) { e = e || window.event; // use e.keycode }); function addevent(element, eventname, callback) { if (element.addeventlistener) { element.addeventlistener(eventname, callback, false); } else if (element.attachevent) { element.attachevent("on" + eventname, callback); } else { element["on" + eventname] = callback; } } in either case, keycode isn't consistent across browsers, there's more check , figure out. notice e = e || window.event - that's normal problem internet explorer, putting event in window.event instead of passing callback.
references:
- https://developer.mozilla.org/en-us/docs/dom/mozilla_event_reference/keypress
- https://developer.mozilla.org/en-us/docs/dom/eventtarget.addeventlistener
with jquery:
$(document).on("keypress", function (e) { // use e.which }); reference:
other jquery being "large" library, jquery helps inconsistencies between browsers, window events...and can't denied. it's obvious jquery code provided example more elegant , shorter, yet accomplishes want in consistent way. should able trust e (the event) , e.which (the key code, knowing key pressed) accurate. in plain javascript, it's little harder know unless jquery library internally does.
note there keydown event, different keypress. can learn more them here: onkeypress vs. onkeyup , onkeydown
as suggesting use, suggest using jquery if you're learning framework. @ same time, should learn javascript's syntax, methods, features, , how interact dom. once understand how works , what's happening, should more comfortable working jquery. me, jquery makes things more consistent , more concise. in end, it's javascript, , wraps language.
another example of jquery being useful ajax. browsers inconsistent how ajax requests handled, jquery abstracts don't have worry.
here's might decide:
Comments
Post a Comment