I have a question. I have made a small site in HTML and vanilla JS to act as a counter. It is working fine, but I wanted to add a function that would allow the user to add or subtract 1 from the counter by pressing "+" or "-", in the numpad or not.
What is the easiest way to do this in vanilla JS?
Sure, just attach to the keyup events and increment or decrement the value when the proper key is pressed.
var value = 0;
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector(".valueHolder").innerHTML = value;
});
document.addEventListener("keyup", function(event) {
if (event.which == "187" || event.which == "107") { // + key
value++;
}
if (event.which == "189" || event.which == "109") { // - key
value--;
}
document.querySelector(".valueHolder").innerHTML = value;
console.log(event.which);
});
<div class="valueHolder"></div>
You will want to add an event listener on the document
document.addEventListener('keydown', myFunction);
function myFunction(e) {
var keyCode = e.keyCode();
...
}
You'll want to look up the keycodes for the keys you will be using (+ and -) and compare that value to keyCode. Then use a conditional to execute your adding or subtracting.
You would create an event handler, which would add or subtract from a global variable based on the key pressed, like this:
window.counter=0;
function key(ev){
if(ev.keycode==107) window.counter++;
if(ev.keycode==109) window.counter--;
}
document.onkeypress = key;
Related
I am new to JavaScript and learning event handlers. How to detect click + specific key pressed concurrently? For example click+D, using pure (vanilla) js.
Edit:
I tried this way but its not detecting the click event when key is pressed.
The console.log("key "+keyPressed) statement is also executed continuously while key is in pressed state.
keyPressed=false;
function keyDown(event) {
var x = event.key;
if (x == "a" || x == "A") {
keyPressed=true;
console.log("key "+keyPressed);
}
}
function keyUp(event){
keyPressed=false;
console.log("key "+keyPressed);
}
function clickHelper(event){
console.log("---");
if(keyPressed){
console.log("*****");
}
}
IIRC you cannot use one event to detect if the mouse is held down AND a button is clicked. However, you can set a property called mouseDown of the document and register an event listener for mouse state.
var mouseDown = 0;
document.body.onmousedown = function () {
++mouseDown;
};
document.body.onmouseup = function () {
--mouseDown;
};
document.body.onkeydown = function (e) {
if (mouseDown && e.key === 'd') {
alert('D was pressed while clicking');
}
};
I used some code from this stackoverflow post for this.
It is possible to program a "Enter" after a value is added to a input text box?
If yes, I need help on my code below. It does't trigger the "ENTER" keypress.
My code as below:
$('#clo_cart').click( function () {
/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;
$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click
Pls Help
Just replace the keydown event with keypress event. There are some differences between how they use event.which property. This might be one of the cases where the two of them use different values for event.which.
var eneterKey = jQuery.Event("keypress");
Also note that which property has been deprecated. You can compare with the event.key property. It should have value Enter when the enter key is to be simulated.
$('#clo_cart').click( function () {
/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.key = 'Enter';
$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}
You can use this code,
$('#clo_cart').click( function () {
var e = $.Event( "keypress", { which: 13 } );
$("#scan_char").focus().val('CLOSECTN').trigger(e);
}//end of bu
This code below work fine for me.
$('#clo_cart').click( function () {
$("#scan_char").focus().val('CLOSECTN').trigger(enterKey());
}//end of button click
/* Function to allow program keypress ENTER */
function enterKey() {
return $.Event( "keypress", { which: 13 } );
}
I want to write a code that if a user press a key, It changes the keyCode or charCode of the User event and trigger the event with a new charcode,
I wrote this code in jsfiddle but this code doesn't work because of too much recursion.
function convert(e, elem) {
function getKey(event) {
if (event.which == null) {
return event.keyCode // IE
} else if (event.which != 0 && event.charCode != 0) {
return event.which // the rest
} else {
return null // special key
}
}
var key = getKey(e);
key++;
return key;
}
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
$(this).trigger(e);
});
<input type="text" class="myInput" />
any Idea that help my code work would be appreciated.
Thanks alot.
Regarding the recursion issue, you need to add a stopping condition, for example:
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
if(!e.isSecondTrigger){
e.isSecondTrigger = true;
$(this).trigger(e);
}});
This way, you only change the value once. However, as was stated by LShetty in the comments section, the event values are read only - you can't change the value of the button that was already pressed and in that way change the input text. In order to do this, you need to manually change the value of the input text after each user action (i.e. hold the value of the input text at each key press, modify it when the user presses a key, and then overwrite the input field value with the output).
Well I searched on Google but still didn't found the answer I was looking for.
I want to check if the user pressed a key, something like this -
if(document.onkeyup) {
// Some Stuff here
}
I know I can do this, this way -
document.onkeyup = getKey;
But the function getKey cannot return values.
So how can I check if the user pressed a key?
EDIT : I need pure Javascript for this thing..
You can do this in pure Javascript using the event object, without the need of external libraries such as jQuery.
To capture the keycode, just pass the event as parameter of getKey function:
function getKey(e)
{
window.alert("The key code is: " + e.keyCode);
}
document.onkeyup = getKey;
Frequently used keyCode list:
For a usefull list of keyCodes, you can check out this URL:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Setting the keyCode to a global variable:
If you are interested in capturing the keyCode for later usage, you can do something like this:
var keycode = "";
(...)
function getKey(e)
{
keycode = e.keyCode;
}
document.onkeyup = getKey;
window.alert("The key code is: " + keycode);
Setting the keyCode to the event source object:
If you don't like global variables, like me, you could also do something like this:
function getKey(e)
{
keycode = e.keyCode;
var objectFromEvent = e.currentTarget ? e.currentTarget : event.srcElement;
objectFromEvent.customProperty = keycode;
}
document.customProperty = "";
document.onkeyup = getKey;
// now the value is in the "customProperty" of your object =)
window.alert("The key code is: " + document.customProperty);
One way you could do it is using variables
and then you could check that variable some were else...
for example
var keypressed = "";
document.onkeyup = function(e){
if (typeof event !== 'undefined') {
keypressed = event.keyCode;
}
else if (e) {
keypressed = e.which;
}
return false; // Prevents the default action
}
You really should not be doing this but if you really must:
var getKey = (function () {
var currentKey = null;
document.onkeyup = function (event) {
// determine the pressed key (across browsers)
// by inspecting appropriate properties of `event`
// and update currentKey; E.g:
currentkey = event.which ? event.which : window.event.keyCode;
}
return function () {
return currentkey;
}
})();
This will give you the last key user pressed.
If you need to get the currently pressed key (until released) then you need to attach keydown event to update currentKey variable and keyup event to set it to null.
You have to attach the event to the window global object and to set a function that listen to the event.
This sample show you how to track the keyup and keydown events.
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
function onKeyDown(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
function onKeyUp(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
See element.addEventListener on MDN for more details.
I would use jquery and do something like this:
// arrow keys click
$(document).keyup(function(e) {
// left arrow
if (e.keyCode == "37" ) {
// left stuff
// right arrow
} else if (e.keyCode == "39") {
// right stuff
// up arrow
} else if (e.keyCode == "38") {
// up stuff
// down arrow
} else if (e.keyCode == "40") {
// down stuff
}
});
etc, for the different key codes seen here http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
If you are attempting to run an event to test when a certain key is pressed, you can use this.
document.addEventListener('keydown', function(event) {
var key_code = event.keyCode;
if (key_code === 38) {
alert('test);
}
});
I have to prevent the form submit if the newVal and oldVal are equal. Else I need to execute the Javascript function. - While pressing Enter key from the key board for the dynamically generated textboxes.
For this case, While pressing enter key the alert is coming repeatedly.
ie, first time one alert. Two alerts for second time.And the expected result is not getting.
What is expected: If I enter a value equals to the curValue then form doesn't have to submit.Else need to call the function myFun(); What is wrong with me?
function pressEnter(id,newValue,i)
{
var newId = '#'+id;
$(newId).keydown(function(event) {
var curValue= '<%=currentVal%>';
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert(newValue+"-"+curValue);
if(newValue== curValue)
{
event.preventDefault();
}
else
{
myFun(i);
}
}
});
}
You have to unbind previous keydown handler:
$(newId).off('keydown').keydown(function(event) {...});
You can do this comparison on form submit event rather than pressing enter key. Because user can use mouse and click the submit button.
Restrict user on form submit as follows,
$("#your_form_id").submit(function() {
var newValue = $(".your_textbox").val();
var curValue= '<%=currentVal%>';
if(newValue== curValue)
{
event.preventDefault();
//Or use return false;
} else{
myFun();
}
});
Here, we can avoid unwanted bind and unbind operations.
And we can achieve this on enter press, just write without function as follows,
$("#your_text_box_id").keydown(function(event) {
var newValue = $(".your_textbox").val();
var curValue= '<%=currentVal%>';
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert(newValue+"-"+curValue);
if(newValue== curValue)
{
event.preventDefault();
}else{
myFun();
}
}
});
Note: If you scope this jQuery code within a function,then javascript add handler for same event on every function call. Result is your code(Code in "keydown" callback) run multiple time. To avoid you have to unbind the event.