I have the following function for example
function RequestInputType(Input) {
inputType: Input
}
So now i want to call this function to cycle throug with an input value if key is pressed.
window.addEventListener('keydown', e => {
if (9 === e.keyCode) {
e.preventDefault();
RequestInputType(0)
//i Want it if key is pressed again then switch from RequestInputType(0) to RequestInputType(1)
RequestInputType(1)
//and if pressed again
RequestInputType(2)
//and so on
}, false);
How do i go about that?
You can create a keydown counter.
var keydownCounter = 0;
window.addEventListener('keydown', e => {
if (9 === e.keyCode) {
e.preventDefault();
keydownCounter++
if(keydownCounter % 3 == 0){
RequestInputType(0)
}
else if(keydownCounter % 3 == 1){
RequestInputType(1)
}
else if(keydownCounter % 3 == 2){
RequestInputType(2)
}
}
},false)
Use a global variable to hold the current argument to pass to requestInputType(). Then you can increment it and wrap around after each call.
let curInputType = 0;
let maxInputType = 3;
window.addEventListener('keydown', e => {
if (9 === e.keyCode) {
e.preventDefault();
RequestInputType(curInputType);
curInputType = (curInputType + 1) % maxInputType;
}
}, false);
Related
Sorry for the vague post. I'm stuck on an online coding challenge, where the objective is that it must be possible to increase and or decrease a number using a keyboard, using the up and down keys. (all HTML-content must be created using JS)
It wants me to use addEventListener without an element object - use the event type keydown. Regardless if the buttons or the up and down keys are used, the decrease button must be 'disabled' if the values in the div-element is '1', and there can't be a number less than '1' in the div element.
Here is my code so far - I'm not sure how to incorporate the functions described above:
addEventListener('load', function() {
let button = document.createElement('input')
let secondButton = document.createElement('input')
button.setAttribute('type', 'button')
button.setAttribute('id', 'increase')
secondButton.setAttribute('type', 'button')
secondButton.setAttribute('id', 'decrease')
document.body.appendChild(button)
document.body.appendChild(secondButton)
let div = document.createElement('div')
div.setAttribute('id', 'bet-size')
div.textContent = '1'
document.body.appendChild(div)
if (Number(div.textContent) === 1) {
secondButton.setAttribute('disabled', '')
}
const increase = function() {
div.textContent = Number(div.textContent) + 1
if (Number(div.textContent) > 1) {
secondButton.disabled = false
}
}
const decrease = function() {
if (Number(div.textContent) === 2) {
secondButton.disabled = true
}
if (Number(div.textContent) > 1) {
div.textContent = Number(div.textContent) - 1
}
}
button.addEventListener('click', increase)
secondButton.addEventListener('click', decrease)
})
You want to use keyDown event's keyCode property to determine the pressed key and call increase() or decrease() accordingly. keyCode stores a number indicating the key that caused the event evocation. There are a number of sites on the internet to determine your desired key code, like this for example.
You also might want to use keyUp to determine key releases again because you might get these events multiple times and only want to react to one of them.
let isKeyDown = false;
const handleKeyDown = function(event) {
if(isKeyDown == false)
{
isKeyDown = true;
if(event.keyCode == 38) // Arrow Up
{
event.preventDefault(); // Prevent page scrolling
increase();
}
else if(event.keyCode == 40) // Arrow Down
{
event.preventDefault(); // Prevent page scrolling
decrease();
}
}
}
const handleKeyUp = function(event) {
if(isKeyDown == true)
{
isKeyDown = false;
}
}
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
Your expanded example might look like this, then:
addEventListener('load', function() {
let button = document.createElement('input')
let secondButton = document.createElement('input')
button.setAttribute('type', 'button')
button.setAttribute('id', 'increase')
secondButton.setAttribute('type', 'button')
secondButton.setAttribute('id', 'decrease')
document.body.appendChild(button)
document.body.appendChild(secondButton)
let div = document.createElement('div')
div.setAttribute('id', 'bet-size')
div.textContent = '1'
document.body.appendChild(div)
if (Number(div.textContent) === 1 ) {
secondButton.setAttribute('disabled', '')
}
const increase = function() {
div.textContent = Number(div.textContent) + 1
if (Number(div.textContent) > 1) {
secondButton.disabled = false
}
}
const decrease = function() {
if (Number(div.textContent) === 2) {
secondButton.disabled = true
}
if (Number(div.textContent) > 1) {
div.textContent = Number(div.textContent) - 1
}
}
// Required to remember if a key is already pressed or not
let isKeyDown = false;
//Event handlers for KeyUp And KeyDown
const handleKeyDown = function(event) {
if(isKeyDown == false)
{
isKeyDown = true;
if(event.keyCode == 38) // Up
{
event.preventDefault(); // Prevent page scrolling
increase();
}
else if(event.keyCode == 40) // Down
{
event.preventDefault(); // Prevent page scrolling
decrease();
}
}
}
const handleKeyUp = function(event) {
if(isKeyDown == true)
{
isKeyDown = false;
}
}
button.addEventListener('click', increase)
secondButton.addEventListener('click', decrease)
//Add the new event handlers to the document's keydown and keyup events
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
})
I want to check the value of a input field against a value in my js object on pressing enter. the if (document.getElementById("barcode").value === element.anr) works. however, i only want it to execute document.getElementById("next").click(); if barcodecounter is equal to element.menge.
Basically if element.menge has a value of 5, the first time document.getElementById("barcode").value is equal to element.anr I want barcodecounter to increase by 1 and when its equal to element.menge it should execute document.getElementById("next").click();.
Currently if e.g. element.menge is 5, it still executes document.getElementById("next").click(); even when I only provided it once instead of 5 times.
What am I doing wrong?
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter = element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
}
else if (document.getElementById("barcode").value != element.anr){
alert("Falscher Artikel");
}
}
});
You are using an assignment = not a boolean compare ==, simple change. I also added some adjustments to the code to initialize stuff. element might be something else but was not in there
// used this but not declared:
//let element = {};
//element.anr = 0;
//element.menge = 0;
//OR use, I assume numerics heres
let element = {
anr: 0,
menge: 0
};
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter = 0;// set initial value;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter == element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
} else /* no need for else if here */ {
alert("Falscher Artikel");
}
}
});
I have a checkbox. If I checks it, it will select all results:
HTML:
<input type="checkbox" id="selectallcheckbox" onClick="toggle(this)" />
And Javascript:
function toggle(source = false) {
if(!source)
{
var source = document.getElementById('selectallcheckbox');
}
checkboxes = document.getElementsByName('id[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
var id = checkboxes[i].id;
var res = id.replace("checkbox", "tr");
if(source.checked)
{
$('#' + res + '').addClass('selected');
} else {
$('#' + res + '').removeClass('selected');
}
}
}
Now I am trying to select all results if I click CTRL+A on my keyboard. Here is my JavaScript:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
toggle();
}
}
});
But this function is not works. How can I make ctrl + a to select all results
The toggle function requires an argument or nothing. When no argument is passed the argument itself can be got directly from the dom. In the html the toggle function get the this keyword. The element itself is passed. But if no argument is passed the argument is undefined and so it can be computed dynamically:
<input type="checkbox" id="selectallcheckbox" onClick="toggle(this)"/>
In the toggle function try to change from:
function toggle(source = false) {
if(!source)
{
var source = document.getElementById('selectallcheckbox');
}
...........
to:
function toggle(source) {
if (source === undefined) {
source = document.getElementById('selectallcheckbox');
}
and, finally, in your jQuery(document).keydown(function(e) { change to:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
// get the argument to the toggle function
var eleObj = document.getElementById('selectallcheckbox');
// toggle the checkbox status
eleObj.checked = !eleObj.checked;
// call the toggle function with the correct argument
toggle(eleObj);
}
}
});
I found solution:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
document.getElementById("selectallcheckbox").click();
}
}
});
From another stackoverflow post (How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?) I have this hotkey code:
function doc_keyPress(e) {
if (e.shiftKey && e.keyCode == 80) {
//do something
}
}
document.addEventListener('keyup', doc_keyPress, false);
which works with two keys. But with three keys, shift + l + m for example, it does not work.
the if statement would be:
if (e.shiftKey && e.keyCode == 76 && e.keyCode == 77) {}
again this does not work.
How do I get this working for shift + l + m.
tricky, tricky, but I managed to get it working. Just be aware that browsers have their own hot keys (like chromes [ctrl]+[shift]+i) which may override the function.
<!DOCTYPE html>
<html>
<body>
<input id="myInput" onkeydown="keyDownEvent(event)" onkeyup="resetKeys()">
</body>
</html>
<script>
var key1Pressed=false;
var key2Pressed=false;
function resetKeys(){
key1Pressed=false;
key2Pressed=false;
}
function keyDownEvent(e){
e=e||event, chrCode=(typeof e.which=="number")?e.which:e.keyCode;
if (e.shiftKey && chrCode === 76) key1Pressed=true;
if (e.shiftKey && chrCode === 77) key2Pressed=true;
if(key1Pressed && key2Pressed){
alert('Three Keys Are Pressed');
key1Pressed=false;
key2Pressed=false;
}
}
document.getElementById('myInput').focus();
</script>
Using a closure, I would envisage you can do something like this
var doc_keypress = (function() {
var prevWasL = false;
return function(e) {
if (e.type == 'keypress') {
if (e.shiftKey && !(e.ctrlKey || e.metaKey)) {
if (prevWasL) {
if (e.charCode == 77) {
console.log('doing it');
prevWasL = false;
return;
}
}
if (e.charCode == 76) {
prevWasL = true;
return;
}
}
prevWasL = false;
} else { // keyup
if (e.key == 'Shift') {
prevWasL = false;
}
}
}
}());
document.addEventListener('keypress', doc_keypress);
document.addEventListener('keyup', doc_keypress);
Add both keypress AND keyup event listeners so that the scenario of
Shift + L, release both, Shift + M, doesn't trigger a false positive
This would require shift then L then M being pressed in that order ... if you want either order of L and M, then the code would be a little different, but you should be able to figure that out
NOTE: I use charCode, because firefox at least, keyCode is always 0 on keyPress event
If you're trying to double press or triple press keys and catch an event after this, I've written a simple helper:
function KeyPress(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
KeyPress.prototype.bubbledReset = function bubbledReset(keyCode) {
var self = this;
if (this.opts.timeouts[keyCode]) {
clearTimeout(this.opts.timeouts[keyCode]);
this.opts.timeouts[keyCode] = 0;
}
this.opts.timeouts[keyCode] = setTimeout(function () {
self.opts.counts[keyCode] = 0;
}, this.opts.timeBetweenPresses);
};
KeyPress.prototype.onTap = function onTap(cb) {
var self = this;
return function handler(event) {
self.opts.counts[event.keyCode] = self.opts.counts[event.keyCode] || 0;
self.opts.counts[event.keyCode]++;
self.bubbledReset(event.keyCode);
cb(event.keyCode, self.opts.counts[event.keyCode]);
};
};
Usage
Simply use the onTap method to instance:
var keyPress = new KeyPress();
document.addEventListener('keyup', keyPress.onTap(function (keyCode, count) {
if (keyCode === 68 && count === 3) {
// 68 was tapped 3 times (D key)
}
if (keyCode === 13 && count === 6) {
// 13 was tapped 6 times (ENTER key)
}
}));
Hope this helps someone else!
Or if you prefer es6:
class KeyPress {
constructor(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
bubbledReset(keyCode) {
if (this.timeouts[keyCode]) {
clearTimeout(this.timeouts[keyCode]);
this.timeouts[keyCode] = 0;
}
this.timeouts[keyCode] = setTimeout(() => {
this.counts[keyCode] = 0;
}, this.timeBetweenPresses);
}
onTap(cb) {
return event => {
this.counts[event.keyCode] = this.counts[event.keyCode] || 0;
this.counts[event.keyCode]++;
this.bubbledReset(event.keyCode);
cb(event.keyCode, this.counts[event.keyCode]);
};
}
}
I'm trying to implement a Tab key listener for a textbox.
$('#mytextbox').live('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// TO DO SOMETHING
}
});
However, for some reason I need to limit the tab listener's callback to invoke only when the textbox has changed. Is there anyway to do this?
You might be able to check the value of the input field to make sure it's different from it's original value?
E.g.
$('#mytextbox').live('keydown', function (e) {
if ((e.keyCode == 9 || e.which == 9) && ($('#TextBox').val() != 'Starting Value')) {
// TO DO SOMETHING
}
});
You can do it just like:
var data = "";
$('#mytextbox').live('keydown', function (e){
if(e.which == 9 || e.keyCode == 9){
if($(this).val() != data){
alert('changed!');
data = $(this).val();
}
}
});
http://jsfiddle.net/DDCZS/1/
Or without storing / knowing value of that textbox:
var changed = false;
$('#mytextbox').on('keydown', function (e) {
if (e.which == 9 && changed) {
e.preventDefault();
// TO DO SOMETHING
alert("works");
changed = false;
} else {
changed = true;
}
});
http://jsfiddle.net/9a37b/