JavaScript: implement sequential keyboard hotkey? - javascript

For example, I want to implement something like do action when you typed sequentially shift-s then s, in JavaScript. I'm inspired by Autohokey, hotkey configuration software/language for Windows, so I'm looking for a library or way to implement something that in JS.
So far I found a library called hotkeys, but I have no idea to implement a sequential keyboard hotkey and didn't find any issue or question about it also, so here I am. So, how can I implement that in JS using the library or other library? Thanks.

This can be done easy with keydown event listener, no library needed for this
sAgain = false
document.addEventListener('keydown', function(event) {
if (sAgain && event.key.toLowerCase() == 's')
alert("shift-s then s clicked")
else if (event.shiftKey && event.key.toLowerCase() == 's')
sAgain = true
else
sAgain = false //stop listen if other key is clicked after shift-s
});
<h1>Press shift s then s<h1>

Related

Distinguish JavaScript events

What is the best way to distinguish events in JavaScript.
Actually there are two points I am interested in. The first one is are there something like id in event (it would be very useful foe debugging purposes). And another point are there better ways to distinguish mousedown and mousedown&touchstart events.
Let me tell you my story. I met the problem that if you add two dom events to a node with triggers mousedown and touchstart, then on mobile devices both mousedown and touchstart run.
The first solution I found was to run
event.preventDefault();
event.stopPropagation();
at the beginning of each listener function.
But then I found out an event delegation pattern and started to work with analytics, all that disallowed to use the previous approach, so I come up with the following solution:
let lastEvent = null;
const specificListener = function(e) {
if (lastEvent === e) {
return; //already run the code due to another listener
}
/*
logic goes here
*/
lastEvent = e;
};
And now I am interested whether or not it is possible to compare events in a different way (different from event1 === event2, hope to find out about something like event1.id === event2.id)?
Thank you.
Instead of trying to differentiate the events, just subscribe to mousedown only, as it is fired anyway. That's the most simple solution I'd say.
Or, you could try to detect which event system is supported and only subscribe to the appropriate one:
var eventType = document.ontouchstart != null ? 'touchstart' : 'mousedown';
document.addEventListener(eventType, (e) => { ... });
A third solution (possibly) would be to use PointerEvents only, but that depends on the platforms you need to support.
https://caniuse.com/#search=pointer%20events
If you for sure cannot use one of these approaches: Every event should have a timestamp property (not sure if it is named that way), maybe you can find a way to distinguish two events with it.

Best practice accessing document object in ReactJS

Is it bad practice to access the document Object directly when working with a framework like React.
I am using an external barcode scanner and I want to detect when number is scanned and populate a specific field. I want to avoid tracking what field is in focus.
Here is my code
render(){
....
document.onkeypress = (e) => {
e = e || window.event;
const digit = e.key;
if(e.target.nodeName === 'BODY' && digit.match(/[0-9]/i)){
console.log(digit);
}
};
document.onkeypress is likely to be poor practice regardless of whether you're using React. Instead, document.addEventListener("keypress", ...) (and be sure to do it only once.)
Separately, hooking up event handlers in render would certainly not be best practice. If you need to hook up a handler to document for some reason, you'd do that in componentDidMount (and you'd remove it in componentWillUnmount).

Triggering an alert with a keypress

I am writing a Greasemonkey script. I want to trigger a certain code to run when the user presses the "Q" key. I did a little bit of research, and most of the sources I saw suggested using window.onkeypress.
To test this method, I created a userscript set to run when the users presses Q. Here is my code:
window.onkeypress = function(event) {
if (event.keyCode == 81) {
alert("This is a test.")
}
}
However, upon pressing the Q key, nothing happened. I am wondering if anyone knows why this may be and what I can do to correct it.
In addition, if anyone knows of any other methods I can use to achieve the same effect, it would be greatly appreciated.
keypress events don’t receive a keyCode; try handling keydown instead.
window.onkeydown = function(event) {
if (event.keyCode === 81) {
alert("This is a test.");
}
};

Setting a timeout for a function call which takes in an event doesn't work with IE7

I'm fairly new to web development and I'd like to think I am getting the hang of it, the only major problems I keep running into are cross-browser compatibility issues.
I have a textarea on a webpage that will call a function after the user is done typing. In order to do this, I am using jQuery and setTimeout to wait a bit before calling the function. This ensures that the function isn't called after every single keypress. I don't want it called after every keypress because the function sends a request to a servlet which does some processing and returns.
The code works fine on Chrome (I use Chrome for debugging it), but it doesn't work with IE7. Here it is:
var timer = null;
$("#scriptInput").keypress(function() {
clearTimeout(timer);
var thisEvent = window.event;
timer = setTimeout(function() {validateScript(thisEvent);}, 500);
});
function validateScript(evt) {
var code = (evt.keyCode) ? evt.keyCode : evt.which;
//check which key was pressed...
//don't need to send a request on key presses of CAPSLOCK, SHIFT, and ARROW keys
if(code != 20 && code != 16 && code != 37 && code != 38 && code != 39 && code !=40){
sendRequest(2);
}
}
As you can see, I've already made numerous attempts at implementing compatibility with IE7, but to no avail :\
It must be compatible with at least IE7 because it will be used by a number of machines which use IE7 and don't have the privileges to upgrade.
Let me know if you need anymore info!
Thanks!
P.S. "scriptInput" is the id of the textarea this is affecting.
var thisEvent = window.event; is not cross-browser compatible - not all browsers use the global event object but a function argument instead.
jQuery always provides you with an event object as a function argument, so simply remove the above assignment and change your code like this:
$("#scriptInput").keypress(function(thisEvent) {
...
});
jQuery also normalizes the various properties for the pressed keys into e.which so you can get rid of var code = (evt.keyCode) ? evt.keyCode : evt.which; and simply use evt.which all the time.
You can also improve/shorten the whole thing a bit more. If adding another library is fine I'd use _.debounce from Underscore.js to do the timing:
$("#scriptInput").keypress(_.debounce(validateScript, 500));
Instead of Underscore.js you could also use a jQuery plugin providing that functionality.
If adding additional third-party code is not an option I'd store the timer on the element instead of a (possibly global) variable:
$("#scriptInput").keypress(function(e) {
var $this = $(this);
window.clearTimeout($this.data('timer'));
$this.data('timer', window.setTimeout(function() {
validateScript(e)
}, 500));
});

Keypress events in Dojo's on module

I have started using Dojo's new on module to add my events. It works fine, but now I've run into a problem. When using keypress event I can't seem to get the character value (for example "2" or "b") from the pressed key. Previously I've used the behaviormodule, and the connect module, and then I have been able to get it by using e.keyChar or e.charOrCode, but now they´re undefined.
I have an event set up like this:
on(element, 'keypress', function(e)
{
console.log(e.keyCode); //works, but not what I need
console.log(e.charOrCode); //undefined
console.log(e.keyChar); //undefined
});
How do I get the character of a pressed key when using this module?
In this case, I think what you want is to use e.keyCode in conjunction with the JS-native String.fromCharCode() in order to get the desired character value.
on(element, 'keypress', function(e) {
var character = String.fromCharCode(e.keyCode);
if (character === 'a') { // do a stuff } else { // do something else }
}

Categories

Resources