Javascript on second keypress - javascript

I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.
var escapeCount = 0;
function reset() {
escapeCount = 0;
setTimeout('reset();', 1000);
}
window.onload = function() {
reset();
};
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (code == 27) escapeCount +=1;
if (escapeCount == 2) {
// stuff on second escape
}
};
Is there a better way to do this? Thanks

It would make sense to reset after 1 second has passed since the last character was pressed. Example:
var lastChar = -1;
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (lastChar == code) {
// Same key was pressed twice in a row within 1 second.
} else {
lastChar = code;
setTimeout(function() {lastChar = -1;}, 1000);
}
};

Your timer resets every second, so you not only have to press Escape again within a second of the last Escape, but that also has to have no timeout in between the presses.
It's probably easier to forget the timeout and just remember the time of the last keypress instead:
var lastescapetime= null;
document.onkeyup= function(event) {
if (event===undefined) event= window.event;
if (event.keyCode===27) {
var now= new Date().getTime();
if (lastescapetime!==null && now<lastescapetime+1000) {
alert('You double-escaped!');
lastescapetime= null;
} else {
lastescapetime= now;
}
} else {
lastescapetime= null;
}
};

Related

Detect difference between key combination and single key

How can I detect the difference between a single CTRL key and a CTRL + 1 key combination?
Currently I have the following:
window.addEventListener('keydown', function(e) {
if(e.keycode === 17){
alert('crtl only')
}
else if (e.ctrlKey && e.keyCode == 49) {
alert('crtl + 1');
}
}
When the key(s) are hit, make a note of the time. Then compare it with the time you noted the last time they key(s) were hit.
If the difference is within your threshold, consider it a double. Otherwise, don't.
If the difference is within your threshold, consider it a double. Otherwise, don't.
Rough example:
var delta = 500;
var lastKeypressTime = 0;
function KeyHandler(event)
{
if ( event.ctrlKey
&& String.fromCharCode(event.charCode).toUpperCase()) == 'T' )
{
var thisKeypressTime = new Date();
if ( thisKeypressTime - lastKeypressTime <= delta )
{
doDoubleKeypress();
// optional - if we'd rather not detect a triple-press
// as a second double-press, reset the timestamp
thisKeypressTime = 0;
}
lastKeypressTime = thisKeypressTime;
}
}
This should work:
window.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode === 49){
alert('combo hit!');
}
}
Use debounce with keydown
function KeyPress(e) {
var evtobj = window.event ? event : e;
debouce(function(evtobj) {
if (evtobj.keyCode == 65 && evtobj.ctrlKey) {
console.log("Ctrl+a");
evtobj.preventDefault();
} else if (evtobj.ctrlKey) {
console.log("Only ctrl");
}
}, evtobj, 200);
}
Demo
function KeyPress(e) {
var evtobj = window.event ? event : e;
debouce(function(evtobj) {
if (evtobj.keyCode == 65 && evtobj.ctrlKey) {
console.log("Ctrl+a");
evtobj.preventDefault();
} else if (evtobj.ctrlKey) {
console.log("Only ctrl");
}
}, evtobj, 200);
}
function debouce(method, eventObj, debounceTime) {
if (this.timeoutId)
clearTimeout(this.timeoutId);
this.timeoutId = setTimeout(function() {
method(eventObj);
}, debounceTime);
}
document.onkeydown = KeyPress;

javascript stop all functions when game is over

I need to stop this function from executing:
document.addEventListener("keypress", function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
checkKey(charStr);
//check loss
if (attempt == 0) {
gameLost();
}
//check win
underscoreRemain = nameReform.includes("_");
if (!underscoreRemain) {
gameWon();
}
document.getElementById("attempt").innerHTML = attempt;
});
Basically, when the game is either won or lost, it won't take any more key pressed, hence no execution of the rest of my functions. I've looked on w3school and stackoverflow, but the removeEnventListener and other suggested methods don't work.
Remove the event listener by passing the original function object to removeEventListener at the appropriate time.
Notice that I gave the function a name.
document.addEventListener("keypress", function handler(evt) {
// evt = evt || window.event; // This line is unnecessary
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
checkKey(charStr);
//check loss
if (attempt == 0) {
gameLost();
// Remove the listener
this.removeEventListener(event.type, handler);
}
//check win
underscoreRemain = nameReform.includes("_");
if (!underscoreRemain) {
gameWon();
// Remove the listener
this.removeEventListener(event.type, handler);
}
document.getElementById("attempt").innerHTML = attempt;
});

Javascript several keyboard events

I'm currently building a music player with three buttons (actually simple divs) for Play/Pause (id="play"), Previous (id=rew) and Next (id="fwd").
I want the Play/Pause to be "clicked" when pressing SPACEBAR.
I want the Previous to be "clicked" when pressing LEFT ARROW.
I want the Next to be "clicked" when pressing RIGHT ARROW.
I've successfully managed the SPACEBAR control of Play with this :
var play = document.getElementById("play");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
};
However, when I add the same for the two other buttons in my script, the SPACEBAR control of Play does not work anymore, as well as the other two.
So, what I have currently in my script and which is obviously not working is this :
<script>
var play = document.getElementById("play");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
};
var rew = document.getElementById("rew");
document.onkeydown = function (e) {
if (e.keyCode == 37) {
rew.click();
}
};
var fwd = document.getElementById("fwd");
document.onkeydown = function (e) {
if (e.keyCode == 39) {
fwd.click();
}
};
</script>
What am I doing wrong ?
Each of your keydown events is overwriting the previous one.
Instead, put all the logic into one keydown event, like this:
var play = document.getElementById("play");
var rew = document.getElementById("rew");
var fwd = document.getElementById("fwd");
document.onkeydown = function(e) {
if (e.keyCode == 32) {
play.click();
} else if (e.keyCode == 37) {
rew.click();
} else if (e.keyCode == 39) {
fwd.click();
}
};
When you assign to onkeydown several times only the last one will be assigned because it will override the previous one. You can use addEventListener instead but that isn't the best approach neither. Just make more test inside one event listener like this:
var play = document.getElementById("play");
var rew = document.getElementById("rew");
var fwd = document.getElementById("fwd");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
rev.click();
}
else if(e.keyCode == 32) {
fwd.click();
}
};

Javascript ActiveElement and Keydown Event Listener

I'm new to Javascript and I'm trying to make the following code scan to see if a textbox with an id="lessonNum" is active, if it is not i would like to send a .click to a submit button with an id="A" when I press 'a' on the keyboard. Right now when I select the textbox I get an alert, but when I don't have it selected it doesn't pick up my keydown. Please Help!
function GetActive () {
if (document.activeElement.id == 'lessonNum') {
alert('lessonNum is active');
var b1=new Boolean(1);
} else {
var b1=new Boolean(0);
}
}
document.addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==65) {
if(b1==0) {
alert('a has been pressed');
document.getElementById('A').click();
}
}
}
In your code:
> function GetActive () {
> if (document.activeElement.id == 'lessonNum') {
> alert('lessonNum is active');
> var b1 = new Boolean(1);
the above line creates a local variable called b1 and assigns a new boolean object. I think you just want a primitive, so:
var b1 = true;
or the whole if..else statement can be replaced with:
var b1 = document.activeElement.id == 'lessonNum';
if (b1) alert('lessonNum is active');
Note that getActive is never called so b1 is never set anyway.
In keyDownTextField you have:
> if(b1==0) {
> alert('a has been pressed');
however b is local to GetActive so a reference error will be thrown. The simple solution is to make b global, a little more work but better though to hold it in a closure.
e.g.
(function(global) {
var b1;
var getActive = function () {
b1 = document.activeElement && document.activeElement.id == 'lessonNum';
if (b1) alert('lessonNum is active');
}
global.getActive = getActive;
var keyDownTextField = function (e) {
e = e || window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == 65) {
getActive(); // should it be called here?
if (b1) {
alert('a has been pressed');
document.getElementById('A').click();
}
}
}
global.keyDownTextField = keyDownTextField;
}(this));
window.onload = function() {
addEvent(document, 'keydown', keyDownTextField);
};
// Just a helper
function addEvent(el, evt, fn){
if (el.addEventListener) {
el.addEventListener(evt, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evt, fn);
}
}

Javascript/jQuery: Convert key combo to string?

I'm looking for an existing Javascript library, or even better, a jQuery plugin, which detects a key combo and outputs the corresponding string (for example, "ctrl+shift+f"). This is to allow a user to configure a key combo for a Google Chrome plugin. The preferences behavior for BetterTouchTool ( http://www.boastr.de/ ) is a good example of what I'm talking about. Has anyone come across something like this?
I think something of this kind might help:
document.onkeydown = KeyDownHandler;
document.onkeyup = KeyUpHandler;
var CTRL = false;
var SHIFT = false;
var ALT = false;
var CHAR_CODE = -1;
function KeyDownHandler(e) {
var x = '';
if (document.all) {
var evnt = window.event;
x = evnt.keyCode;
}
else {
x = e.keyCode;
}
DetectKeys(x, true);
DoSometing();
}
function KeyUpHandler(e) {
var x = '';
if (document.all) {
var evnt = window.event;
x = evnt.keyCode;
}
else {
x = e.keyCode;
}
DetectKeys(x, false);
DoSometing();
}
function DetectKeys(KeyCode, IsKeyDown) {
if (KeyCode == '16') {
SHIFT = IsKeyDown;
}
else if (KeyCode == '17') {
CTRL = IsKeyDown;
}
else if (KeyCode == '18') {
ALT = IsKeyDown;
}
else {
if(IsKeyDown)
CHAR_CODE = KeyCode;
else
CHAR_CODE = -1;
}
}
function DoSometing() {
//check for keys here
}
I hope it'll be useful
$(document).keypress(function(e) {
alert(
(e.ctrlKey ? 'ctrl+' : '') +
(e.altKey ? 'alt+' : '') +
(e.shiftKey ? 'shift+' : '') +
String.fromCharCode(e.which).toLowerCase()
);
});
This will register the keys; not sure how you're going to block the ctrl/alt keys from getting interpreted though.
browser support: http://www.quirksmode.org/js/keys.html
I forgot I even asked this question! After many months, I've written a plugin myself that does exactly this =)
http://suan.github.com/jquery-keycombinator/

Categories

Resources