Create KeyEvent in Javascript - javascript

I have the following problem - I'm catching a key event an I need to create a new altered key event(since it seems the keyCode property is read-only) and afterwards handle the newly created KeyEvent. I came across several old posts in StackOverflow where similar situations are handled, but:
I need this to be working under Webkit /there's a solution here in StackOverfow but it is working only in Gecko/
I need to create another KeyEvent, but not TextInputEvent, since the TextInputEvent will only let my specify a string to be inserted, whilst I cannot do that as I use a third party tool that needs to handle this event and I need a keycode.
I tried jQuery#trigger() but it won't work for me. My code is as follows
var event = jQuery.event('keydown');
event.which = 13; //I'm trying to simulate an enter
$('iframe').contents().find('document').find('body').trigger(event); //my content is inside an iframe

(function($){
$(window).load(function(){
var e = $.Event("keydown");
e.which = 13;
e.keyCode = 13;
$('iframe').contents().find('html, body').trigger(e);
});
})(jQuery);

Related

If key pressed then, Javascript

I made this game counter: https://mikesgames.neocities.org/Games/Cursor%20Counter/counter.html for my friends and I (I'm in middle school so it doesn't have to be perfect).
I want to have a feature where someone presses the key(cursor) the game grants the initiator 10,000 points (in my game its cursors).
I believe I will need JavaScript for this. I have a little cheat button like this-
<div class="button" onclick="cheat()"></div>
btw I'm using https://neocities.org
Add the following Javascript to call the cheat method when N is pressed
document.onkeydown = function(e){
e = e || window.event;
var key = e.which || e.keyCode;
if(key===78){
cheat();
}
}
If you want to add additional functionality for other keys then a useful list can be found here - https://css-tricks.com/snippets/javascript/javascript-keycodes/

Using keyCode to pair keydown and keyup events

I want to keep track of which keys are pressed at a given time, like so:
var keys = {};
$(document.body).on('keydown', function(e) {
keys[e.keyCode] = true;
});
$(document.body).on('keyup', function(e) {
delete keys[e.keyCode];
});
However, from MDN it looks like keyCode is deprecated, and suggests key. From testing on Chrome, it looks like key is undefined. The documentation also describes which but I am unsure as to what the differences are.
Is keyCode the right thing to use here? I don't care which keys are down, only that I know that some keys are pressed. I also can't use the input event.
I would suggest to use a fallback mechanism which handles the advise from MDN first and than falls back to the older solutions.
But if you are using jQuery you should use the provided methods to get the key-code
// jquery
$(document.body).on('keyup', function(e) {
delete keys[e.which];
});
// vanilla
document.body.addEventListener('keyup', function (e) {
delete keys[(e.key && e.keyCode.charCodeAt(0)) || e.which || e.keyCode];
}, true);
However this will only be true for printable characters and needs a deeper investigation of the problem usually.

Detect shiftKey for mouse event on google maps v3 polygon

Is there a way to detect a shift-mouseclick on a polygon when using the google maps V3(.16) javascript API?
https://developers.google.com/maps/documentation/javascript/reference#MouseEvent
I do receive the mouse event, and I can see that the original event is wrapped in a google event class, which is just what's needed (Access the event.Ua.shiftKey property).
I found however that last month, google may have updated their api and now the property is renamed to event.Pa.shiftKey.
For reference, see http://i.stack.imgur.com/80npD.png for a screenshot of the event structure in the webinspector.
Is there any way to detect whether the shift key is pressed during a click on a google maps polygon using the event, and without having to rely on google-not-updating-their-api? What am I missing?
Thx!
Using undocumented properties is almost always a bad idea. If you can possibly avoid it, avoid it. In this case, the API is probably being compressed with the Closure Compiler, and so the next time they update, it may not be Pa anymore either.
Is there any way to detect whether the shift key is pressed during a click on a google maps polygon using the event, and without having to rely on google-not-updating-their-api?
If just Ua vs. Pa:
You could feature detect:
var shiftKey = (event.Ua || event.Pa).shiftKey;
That uses JavaScript's curiously powerful || operator to reference the Ua property's value, if there is one and it's truthy, or the Pa property's value otherwise.
This assumes that when they change it from Ua to Pa, they don't use Ua for something else. If there's a chance of that, this more thorough version would do it:
var shiftKey = ((event.Ua && 'shiftKey' in event.Ua) ? event.Ua : event.Pa).shiftKey;
That specifically checks for a Ua object with a shiftKey property, falling back to Pa if not found.
If it could be anything
...you can search for it:
var shiftKey;
if (Object.keys(event).some(function(key) {
if (event[key] && 'shiftKey' in event[key]) {
shiftKey = event[key].shiftKey;
return true;
}
return false;
})) {
// We found it, `shiftKey` has the value
} else {
// We didn't find it
}
Side note: Object.keys is an ES5 feature present on all modern browsers. If you need to support older browsers like IE8, it can be polyfilled.
I've just come across this problem (after noticing I couldn't just use window.event because Firefox doesn't support it)
google.maps.mouseEvent has, as T.J. Crowder said, a property which contains keys such as shiftKey, altKey, etc. In the current release of google maps api, said property is va. So of course we can't use it because its name will change in the next release of so.
So my solution has been to iterate over the google.maps.mouseEvent parameter, checking its values so see which one of them is a valid window.MouseEvent.
var newcircle= new google.maps.Circle({map:map, position:map.getCenter(), radius:1000});
google.maps.event.addListener(newcircle,'click',function(mouseEvent) {
var event = Object.values(mouseEvent)
.filter(function (property) {
return property instanceof window.MouseEvent;
});
if (event.length) {
event = event[0];
} else {
event = {};
}
var shiftKey = event.shiftKey || false;
});
Funny enough, when I tried to use a marker for this example, there wasn't an instance of window.MouseEvent in the google.maps.mouseEvent.
I ended up with a solution close to amenadiel's answer. I thought it would be better not to relay on all the possible uglified variable names, but to look for the one being a MouseEvent and use that one to check for the shiftKey property, like this:
function polygonListener(polygonEvent) {
var shiftKey = false;
for(var i in polygonEvent){
if(polygonEvent[i] instanceof window.MouseEvent){
shiftKey = polygonEvent[i].shiftKey;
break;
}
}
// Rest of the code
}
In case anyone is still looking how to get the MouseEvent from a google maps event, this is the method I've been using.
const mouseEvent = Object.values(event).find(p => p instanceof window.MouseEvent);
// then do whatever with the MouseEvent
const shiftKey = mouseEvent.shiftKey;

Keycode is always zero in Chrome for Android

I need to detect the keycode for a custom search box on my website, but the keycode always returns as zero on Chrome for Android (except for backspace, which returns 8). Has anyone else experienced this, and how did you get around it? Our website works on all mobile browsers except Chrome for Android because we can't detect a non-zero keycode or charcode.
I'm running Chrome 27.0.1453.90 on Android 4.1.2 Jelly Bean. The problem can be duplicated with something as simple as:
alert(event.keyCode);
below solution also work for me. might be useful for others also.
var getKeyCode = function (str) {
return str.charCodeAt(str.length - 1);
}
document.getElementById("a").onkeyup = function (e) {
var kCd = e.keyCode || e.which;
if (kCd == 0 || kCd == 229) { //for android chrome keycode fix
kCd = getKeyCode(this.value);
}
alert(kCd)
}
I faced this issue and this is how I figured out how to solve the problem.
First, you need to enable USB debugging onto your Android phone so
you can see the logs of your browser on your desktop machine.
Second, refresh your web app on your phone and inside your console on the desktop type "monitorEvents(document)" or whatever element you want to inspect.
Do the action you want to inspect on your phone.
And this is how I found that the keydown event was actually fired by a unique event called "textInput" which contains the information inside event.originalEvent.data.
Hope this saves you time and good luck!
The true way to get the keyCode is to use
event.which
This property on event object is standardize the event.keyCode property. You can read about it also in jQuery documentation here or in MDN here
In other way, I have a lot of experience with keyboard events on android devices.
Android browser has problems sometimes with keyboard events due to device fragmentation (different ROMs between devices or external keyboard apps). The best way is to try to use all the keyboard events (keydown, keyup and keypress) and compare every result to get the pressed key.
The best way is to use in "input" event and get all the time the last charter. The input event can control like in my answer here.
We encountered this problem recently on a China made Android phone Meizu MX3, which has a deeply customized OS based on Android 4.4.4.
The default browswer and Chrome work just fine, but for some weird reasons we don't know, event.keyCode, event.charCode and event.which return 0 all the time in some other browsers(such as CM Browser or webview of Wechat app).
We resolved this by checking the last character you input such as 'A' or ' '(space), then we convert it to ascii code using charCodeAt such as "A".charCodeAt(0) which returns 97, which is the actual char code we need.
But we can only determine the char code of visible chars using this strategy, which meets our current need thank god.
Hope you guys can get some inspiration from this.
I have faced the same issue with Android Devices of SonyXperia and HTC. I have developing hybrid application where i am validating Amount text field by reading event.keyCode() of the entered char on keydown event from text field, so that i can allow only numbers and dot(.) char to be entered. I tried but it doesn't worked, returning always 0 in these devices.
Later i came with other solution with keyup event and char matching through Regular Expression:
$("#AmountField").keyup(function (e) {
var regex = /^[0-9\.]$/;
var str = $(this).val();
var subStr = str.substr(str.length - 1);
if(!regex.test(subStr)) {
if(str.length >0){
$(this).val(str.substr(0, (str.length - 1)));
}else{
$(this).val();
}
}
});
Hope this can help for the people who facing this issue. Good Luck.
<input type="text" id="char" size="15" onblur="showKeyCode()" value="a">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
<script>
function showKeyCode()
{
var character = document.getElementById ( "char" ).value.substr(this.length - 1);
var code = character.charCodeAt();
var stringall = document.getElementById ( "char" ).value;
var msg = "The Key Code for the \""+character+"\" character is "+code+".";
alert(msg);
}
</script>
For reference
If anybody still digging it.Problem appears on stock Samsung keyboard for
android devices.
Instead use onkeyup.
change the type of the input to tel : <input type="tel">
this will let you log the keyCode but it doesnt log the backspace, and it might force the keyboard on mobile to only numbers.
So in most Android browser if u use keydown or keyup you wont be able to get the data from key or keyCode or which or code
You can use event.data(Inserted data key) and event.inputType(backspace or del in mobile)
In order to achieve the functionality you need you have to apply condition based on user agent for android mobile
if (navigator.userAgent.match(/Android/i)) {
node.addEventListener('input', handleInput, false);
} else {
node.addEventListener('keydown', handleKeyDown, false);
}
const handleKeyDown = event => {
event.preventDefault();
if (!event.key) {
return false;
}
genericFunctionHandleThings(event.key, event.code === 'Backspace');
};
const handleInput = event => {
event.preventDefault(); // Here event.preventDefault doesn't stop user from typing
genericFunctionHandleThings(event.data, event.inputType === 'deleteContentBackward');
node.value = storedOrProcessedValue;
};
Here I have used node.value = storedOrProcessedValue because if we want to make some restriction for user typing we need to process and re assign it to the input
You can use this with Input type text,url,email,tel these I have tested rest I need to check
Need to use charCode instead of keyCode
<input type="text" onKeyPress="return funName(this,event)" />
<script language="javascript">
function funName(th,ev)
{
alert(ev.charCode);
}
</script>

Having problems with the mouseup event

Hello I am working on two functions swapFE() and swapEF(). The purpose of these two functions is to exchange the French phrases with the English phrases which I've already done.
When I press the mouse button down on each phrase the English translation appears which is what i want it to do.
The problem is when I release the mouse button the French phrase should reappear and it doesn't happen. I don't know what I'm doing wrong.
I would appreciate it if someone can help me. Thanks for your time and for your help.
function swapFE(e){
var phrase = e.srcElement;
var parent = phrase.parentNode;
var idnum = parent.childNodes[0];
var phrasenum = parseInt(idnum.innerHTML)-1;
phrase.innerText = english[phrasenum];
phrase.className ='english';
}
function swapEF(e){
var phrase = e.srcElement;
var parent = phrase.parentNode;
var idnum = parent.childNodes[0];
var phrasenum = parseInt(idnum.innerHTML)-1;
phrase.innerText = french[phrasenum];
phrase.className ='french';
}
Without seeing your html it's difficult to determine if your issue is (1) your javascript method (I'm assuming swapEF) isn't working correctly or (2) the assignment of your event handler is not working or both. Make sure you are using the correct event functions ( "mousedown" and "mouseup") and try to test your functions manually in a javascript debugger like firebug or the Chrome javascript console. That will help you pinpoint the issue and fix your problem, but without the html and the assignment of your event handler it is difficult to post a solution.

Categories

Resources