Problem with event handler - javascript

function getFieldName(e) {
e = e || window.event;
var key = e.keyCode || e.which,
target = e.target || e.srcElement;
alert(target.name);
return (key != 13);
}
I have the above function called on body tag onkeypress = getFieldName(event);
I get the name of desired field but not able to check in IE as well as FF
if(target.name == 'check') {
// works fine in FF but in IE I'm not able
// to come inside this if-block, please suggest
}
thanks

I see you've tagged this post as jQuery... If you actually use jQuery to manage the event handler then you can use e.which to find the key that was pressed and e.target to find the DOM target. It also worries about the cross-browser stuff for you.
To attach a function as an event handler, you can follow this simple example:
$(document).keypress(getFieldName);

jQuery already normalizes some event properties internally, so you can just use event.target and event.which, you don't need to check for others, like this:
$(document).keypress(getFieldName);
function getFieldName(e) {
alert(e.target.name);
if(e.which == 13) {
alert("Key pressed was enter");
} else {
alert("Key pressed was not enter");
}
}
​
You can view a quick demo here

Related

JavaScript onkeydown not functioning

I'm trying to setup a text box that runs a function on keydown.
The code is:
var input = document.getElementById('Input_Number');
input.addEventListener('onkeypress', DrawDigits);
function DrawDigits(event) {
if (event && event.keyCode == '13') {}
}
Here's an example:
http://jsfiddle.net/wuK4G/
I know this is a common question, but I really can't find the answer. I've tried several methods and none of them work.
Try this:
function DrawDigits(event) {
if (event && event.keyCode == '13') {}
}
var input = document.getElementById('Input_Number');
input.addEventListener('keypress', DrawDigits);
// ^^
The eventlistener is keypress instead of onkeypress.
If you assign the eventlistener without addEventListener it is:
document.getElementById('Input_Number').onkeypress = DrawDigits
Maybe that was the confusion?

How do I get key values in HTML/Javascript

Okay, so i understand how to get the key value while using an input field... but I am taking about key values that are pressed while your browser isn't focused in any text box or text area.
I am trying to make a onscreen keypad that has buttons for 0, 1, 2, .. 9... however I want the user to be able to press the buttons with the keys on the keyboard.
I've seen this done in some websites, where if you press the S key on the homepage, it will take you to the signin screen. Facebook also does the L key, to like a photo.
So the question is: How do I get the key values in javascript, when the cursor isn't focused.
If you are using JQuery you just add the event handler to the document...
$(document).keypress(function(event) {
alert('Handler for .keypress() called. - ' + event.which);
});
(From http://forum.jquery.com/topic/how-to-catch-keypress-on-body)
Edit for zzzzBov's comment...
From the JQuery KeyPress documentation:
To determine which character was entered, examine the event object
that is passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the character code.
you need to use window.onkeydown and then check for the keys you're interested in.
https://developer.mozilla.org/en-US/docs/Web/API/window.onkeydown
You should listen on key press event.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
alert("Character typed: " + String.fromCharCode(charCode));
};
For more info Look here Link
You need to add an event listener to the window. Then in the event handler, you get the keyCode property from the passed-in event. KeyCodes are semi-arbitrary in that they don't directly map to what you might think, so you have to use a table (first result on google: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) to identify the keycodes you care about.
window.addEventListener('keypress',function (evt) {
switch (evt.keyCode) {
case 48:
zeroKeyPressed(); break;
case 49:
oneKeyPressed(); break;
...
}
}, false);
You would use a key press event.
Here's an example for your usage:
window.addEventListener('keypress', function (event) {
var key_code, key;
event = event || window.event; // IE
key_code = event.charCode || event.keyCode || event.which || 0;
key = String.fromCharCode(key_code);
// prevent keys 0-9 from doing what they normally would do
if (key_code >= 48 && <= 57) {
event.preventDefault();
alert('The user pressed ' + key);
}
}, false);
Using plain js, you can use this in your layout.htmlcs, at the beginning:
#{
<script>
sessionStorage.setItem("ProductionHostURL", '#System.Configuration.ConfigurationManager.AppSettings["ProductionHostURL"]');
</script>
}
<!DOCTYPE html>
Then in your main js file of the layout.htmlcs, you can use this a method liked this:
var urlBaseProduction;
var urlBaseDevelopment;
$(document).ready(function () {
configureHostEnvironment()
....
}
In that method, configure the variables to use in production and development, like this:
function configureHostEnvironment(){
HOST = sessionStorage.getItem("ProductionHostURL")
if (HOST.length <= 0) {
alert("Host not configured correctly")
} else {
urlBaseProduction= host + '/api/';
urlBaseDevelopment= host + port + '/api/';
}
}
If you have a suggestion or improvement to this method, please comment.

How can I generate a keyup event with a specific keycode in IE8?

I need to generate keyup events in IE 8 using native DOM functions (no jQuery). The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the keyCode?
<form><input id="me" type="submit" /></form>
<script type="text/javascript">
var me = document.getElementById("me");
me.attachEvent("onkeyup", function(e) {
alert(e.keyCode); // => 0
});
document.getElementById("me").fireEvent('onkeyup', 13);
</script>
Figured it out. The solution is to create an event object, assign the keycode, and fire it from the node.
var e = document.createEventObject("KeyboardEvent");
e.keyCode = keyCode;
node.fireEvent("onkeyup", e);
e = e || window.event;
keycode = e.keyCode || e.which;
That will make events work in all browsers.
Also, I prefer to use me.onkeyup = function(e) { ... }, but that' just personal preference (I know the drawbacks of this method, but I have clever ways to work around them)

Javascript event handler on body but not on input

I have the following event handler
document.addEventListener('keydown', handleBodyKeyDown, false);
HOW DO i prevent it from occurring when inside a input box
Within your handleBodyKeyDown function, check if
event.target.tagName.toUpperCase() == 'INPUT'
(or 'TEXTAREA').
Note: For older versions of IE, use event.srcElement.tagName.
Like so:
document.addEventListener('keydown', handleBodyKeyDown, false);
function handleBodyKeyDown(event)
{
var e = event || window.event,
target = e.target || e.srcElement;
if (target.tagName.toUpperCase() == 'INPUT') return;
// Now continue with your function
}
P.S. Why are you using addEventListener if you have jQuery on the page? In jQuery, all of this gets sorted out for you:
$(document).on('keydown', ':not(input)', function(e)
{
// Your code goes here...
});
In your handleBodyKeyDown method, check to see if the event originated on an input element:
function handleBodyKeyDown(event) {
if (event.target.tagName.toUpperCase() === 'INPUT') {
return; // do nothing
}
// do the rest of your code
}
Note that the toUpperCase call is necessary because the conditions that determine the case of the tagName property are quite complicated and sometimes all but uncontrollable.
See event.target at MDN.
If you are using jQuery you can try this which uses is() method to test the target element is input then do nothing.
function handleBodyKeyDown(event) {
if ($(event.target).is("input")) {
return;
}
else{
//Do your stuff here
}
}
This worked for me:
const fromInput = event => event.srcElement instanceof HTMLInputElement;
function handleBodyKeyDown(event) {
if(fromInput(event))
return;
// do your magic here
}
You could do something like:
handleBodyKeyDown = function(e) {
var e = e || window.event
if (e.target.tagName != "INPUT") {
// handle this since it isn't input
}
}
Sometimes (as to me) it is better not to prevent it to occur, but to ignore in the event cases, when it occured in the input. It's looks like this is also your case as well.
Just inspect evt.target || evt.srcElement property (modern frameworks do this normalization work for you, so, most probably this will be called target) whether it's input or not. If not, just ignore.
QuirksMode tells you how to get an event's target. You can check that it is not an input:
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
if( targ.tagName != "INPUT" ) {
//Perform your action here
}
}
Your question is tagged jQuery, in which case you can just test event.target as the framework normalizes this for you.
$(document).bind("keydown", function (event) {
if(event.target.tagName != "INPUT") {
//Do something
}
});
HandleBodyKeyDown function will be invoked in any case. You can not prevent its call on the method of recording as you indicated. You can only add a logic for checking if this an 'input' and return. Additionaly (if needed) you can prevent it from bubble up:
function handleBodyKeyDown(ev) {
ev=ev||event;
var sender=ev.target||ev.srcElement;
if(sender.tagName.toLowerCase()==="input") {
if(ev.stopPropagation)ev.stopPropagation();
else ev.cancelBubble=true; // for IE8 or less
return true; // do not prevent event from default action
}
// your code for global keydown
}
If you're using Prototype (which you have tagged but you also have two other frameworks tagged) then the event can be registered and filtered in one like this:
document.on('keydown', ':not(input)', handleBodyKeyDown);

How to listener the keyboard type text in Javascript?

I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?
To do it document-wide, use the keypress event as follows. No other currently widely supported key event will do:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
I use jQuery to do something like this:
$('#searchbox input').on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
EDIT: Since you're not binding to text box use:
$(window).on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
http://docs.jquery.com/Main_Page
You can listen for the onkeypress event. However, instead of just examining either the event.keyCode (IE) or event.which (Mozilla) property which gives you the key code, you need to translate the key code using String.fromCharCode().
A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt) function.
Additional references: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode() method.
This is too complicated to answer quickly. This is what I use as the definitive reference for keyboard handling. http://unixpapa.com/js/key.html

Categories

Resources