Javascript ActiveElement and Keydown Event Listener - javascript

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);
}
}

Related

get keycode with shiftkey

I want to get keyCode if they are pressed with shift Key,
for ex. I press a and then b. Then I want to store it in one array like this [shiftkey,65,66] please suggest me if this is possible or I am going wrong.
You can try this sanjay:
<input id="down" type="text"/>
var your_array = [];
document.onkeydown = function (e) {
var keyPress;
if (typeof event !== 'undefined') {
keyPress = this.value + String.fromCharCode(e.keyCode);
}
else if (e) {
keyPress = e.which;
}
if(keyPress == '16'){
keyPress = 'shift';
}
your_array.push(keyPress);
alert(your_array);
// returns [shift,65,66];
return false; // Prevents the default action
};
var a = [];
var wait = true;
window.onkeydown = function (e) {
if (wait) {
if (a[0] != e.keyCode) { a[0] = e.keyCode; }
}
wait = false;
window.addEventListener('keyup', key_up, false);
}
function key_up(e) {
a[1] = e.keyCode;
if (a[0] == a[1]) { a = []; }
wait = true;
window.removeEventListener('keyup', key_up, false);
console.log(a);
alert(a);
}
var pressedKeysSeries = [];
$(document).on('keyup', function (e) { pressedKeysSeries = []; });
$(document).on('keydown', function (e) {
if (e.shiftKey && pressedKeysSeries.indexOf(e.key) === -1) {
pressedKeysSeries.push(e.key);
}
console.log(pressedKeysSeries);
});

How to access function from event listener. JavaScript

I have an event listener in header:
window.onkeydown = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if(key == 27) {
var panel = document.getElementById('largeImgPanel');
hideMe(panel);
}
if(key == 39) {
arrow_right.onclick = onRight; //Wrong
}
};
Lower i have a function:
window.onload = function() {
...
var onRight = function showNext(img_thumb) {
index = index + 1;
document.getElementById('largeImg').src = arr_big[index].src;
showLargeImagePanel();
unselectAll();
};
arrow_right.onclick = onRight;
My question is:
How i can "execute" onRight variable from event listener?
Allow onRight to be a global variable. Although this is not always desirable, in this instance it will work. Keep in mind, it is best not to pollute the global namespace.
window.onRight = function showNext(img_thumb) {...
and then later you may access it the same way
arrow_right.onclick = window.onRight;

How to detect keyboard modifier (Ctrl or Shift) through JavaScript

I have a function which detect max length. but the problem is that when the max length reached Ctrl+A combination does't work. How can I detect Ctrl+A combination through javascript.
This is my maxlength code.
if (event.keyCode==8 || event.keyCode==9 || event.keyCode==37 || event.keyCode==39 ){
return true;
} else {
if((t.length)>=50) {
return false;
}
}
Check event.ctrlKey:
function keyHandler(event) {
event = event || window.event;
if(event.keyCode==65 && event.ctrlKey) {
// ctrl+a was typed.
}
}
key codes:
shift 16
ctrl 17
alt 18
your jQuery:
$(document).keydown(function (e) {
if (e.keyCode == 18) {
alert("ALT was pressed");
}
});
JavaScript Madness: Keyboard Events
You can use the following:
document.onkeypress = function(evt) {
evt = evt || window.event;
etv = evt;
switch (etv.keyCode) {
case 16:
// Code to do when Shift presed
console.log('Pressed [SHIFT]');
break;
case 17:
// Code to do when CTRL presed
console.log('Pressed [CTRL]');
break;
case 32:
// Code to do when ALT presed
console.log('Pressed [ALT]');
break;
}
};
I needed a solution for this too, so found some stuff that worked, cleaned it up to be a lot less code, and ES6... JSFiddle link
function isCapsLock(event=window.event) {
const code = event.charCode || event.keyCode;
if (code > 64 && code < 91 && !event.shiftKey) {
return true;
}
return false;
}
document.getElementById("text").addEventListener("keypress", event => {
const status = document.getElementById("status");
if (isCapsLock(event)) {
status.innerHTML = "CapsLocks enabled";
status.style.color = "red";
} else {
status.innerHTML = "CapsLocks disabled";
status.style.color = "blue";
}
}, false);
<input type="text" id="text" /><br>
<span id="status"></span>
This is a very old question. gilly3's answer is valid only if we have at hand an event object of type KeyboardEvent passed as a function argument. How to detect the current control key state if we have not event object available such as in this function?
function testModifierKey() {
// have I some modifier key hold down at this running time?
}
I found the solution after a long search from https://gist.github.com/spikebrehm/3747378 of spikebrehm. his solution is tracing the modifier key state at any time using jQuery with a global variable.
The global variable window.modifierKey can be used in any circonstance without requiring event object.
function testModifierKey() {
// have I have some modifier key hold down at this executing time?
if(window.modifierKey) {
console.log("Some modifier key among shift, ctrl, alt key is currently down.");
// do something at this condition... for example, delete item without confirmation.
} else {
console.log("No modifier key is currently down.");
// do something at other condition... for example, delete this item from shopping cart with confirmation.
}
}
Here is his script to load in your HTML document:
// source: https://gist.github.com/spikebrehm/3747378
// modifierKey used to check if cmd+click, shift+click, etc.
!function($, global){
var $doc = $(document);
var keys;
global.modifierKey = false;
global.keys = keys = {
'UP': 38,
'DOWN': 40,
'LEFT': 37,
'RIGHT': 39,
'RETURN': 13,
'ESCAPE': 27,
'BACKSPACE': 8,
'SPACE': 32
};
// borrowed from Galleria.js
var keyboard = {
map: {},
bound: false,
press: function(e) {
var key = e.keyCode || e.which;
if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) {
keyboard.map[key].call(self, e);
}
},
attach: function(map){
var key, up;
for(key in map) {
if (map.hasOwnProperty(key)) {
up = key.toUpperCase();
if (up in keyboard.keys) {
keyboard.map[keyboard.keys[up]] = map[key];
} else {
keyboard.map[up] = map[key];
}
}
}
if (!keyboard.bound) {
keyboard.bound = true;
$doc.bind('keydown', keyboard.press);
}
},
detach: function() {
keyboard.bound = false;
keyboard.map = {};
$doc.unbind('keydown', keyboard.press);
}
};
$doc.keydown(function(e) {
var key = e.keyCode || e.which;
if (key === 16 || key === 91 || key === 18 || key === 17) {
modifierKey = true;
} else {
modifierKey = false;
}
});
$doc.keyup(function(e) {
modifierKey = false;
});
}(jQuery, window);

Javascript keyboard event in an object

I got my keyboard working in a simple way:
rightPressed = false;
onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = true;
}
onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = false;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
And it worked. Then i tried to put it all in a class:
function Tkeyboard(){
this.rightPressed = false;
this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
}
$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}
In initialization I created an object:
keys = new Tkeyboard;
In main loop i put action:
if ( keys.rightPressed ) { rx+=1;}
And now it fails. The interesting part of the problem is that alert("boom!") is called, so variable should get modified too...
I would be grateful for any ideas.
The keydown/up callback loses its original scope when the it is actually run. You'll need to bind the callback to this. In the Prototype Framework, you would do this:
function Tkeyboard() {
this.rightPressed = false;
$(document).keydown(this.onKeyDown.bind(this));
$(document).keyup(this.onKeyUp.bind(this));
}
Tkeyboard.prototype.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
};
Tkeyboard.prototype.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
};
It should be similar in jQuery.
If you need an idea of how to build a full fledged keyboard class, check out the one I wrote.
In an event handler in jQuery (and in DOM events), this refers to the element the event is subscribed on (document in the sample). Use a closure if you want to refer to the original object.
function Tkeyboard(){
var self = this;
this.rightPressed = false;
this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { self.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { self.rightPressed = false; }
}
$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}
this is set to the DOM element (in this case document) from which the event handler is called. In general, this is not bound to the object in javascript:
var a = {
f: function () {}
};
var b = { f: a.f};
var f = a.f;
a.f(); // this === a
b.f(); // this === b
f(); // this === window
One commonly used workaround is to bind this to a wrapper function:
function bind(func, that) {
return function() {
func.apply(that, arguments);
}
}
//...
$(document).keydown(bind(this.onKeyDown, this));
Or you could use closures:
function Tkeyboard() {
var that = this;
// use 'that' from here on
you can initiate new function it will work
function Tkeyboard() {
this.rightPressed = false;
this.onKeyDown = function (pressEvent) {
if (pressEvent.keyCode == 39) {
this.rightPressed = true;
console.log(this.rightPressed )
alert('boom')
}
}
this.onKeyUp = function (pressEvent) {
if (pressEvent.keyCode == 39) {
this.rightPressed = false;
console.log(this.rightPressed )
}
}
this.events = function(){
document.addEventListener('keydown', this.onKeyDown);
document.addEventListener('keyup', this.onKeyUp);
}
}
const keys = new Tkeyboard;
keys.events();

Javascript on second keypress

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;
}
};

Categories

Resources