increase number when I press arrow key on keyboard with javascript - javascript

I have a textbox has a numeric value.
now what I want is to keep increasing that numeric value while im pressing and holding any of arrow keys.
I know how to do this if I was pressing only one time. it will be increased by 1 only. but what If I want to keep increasing the value while i'm holding the arrow keys. how to do that?
thanks

There's a small jQuery plugin for doing this:
https://github.com/nakupanda/number-updown
Usages:
$('#simplest').updown();
$('#step').updown({
step: 10,
shiftStep: 100
});
$('#minMax').updown({
min: -10,
max: 10
});
$('#minMaxCircle').updown({
min: -10,
max: 10,
circle: true
});
View live demo here:
http://jsfiddle.net/XCtaH/embedded/result/
Keyboard and mousewheel events supporte

This is not fully tried and tested by me, but here is a thought - You might want to track KeyDown events because that's the event which is queued by the OS when the key is first pressed. You might also want to implement some sort of delay when incrementing this way so as not to overwhelm the client-side script and have numbers change at a speed to high for user to track.

ok after some tests I made here is how its done:
var setTimeoutId;
var keyIs = "up";
function myIncrementFunction()
{
var num = parseFloat(myText.value)+1;
myText.value = num;
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
{
var e = e || event ;
if (e.keyCode == 38)
{
for(var s=0; s<1; s++)
setTimeoutId = setTimeout('myIncrementFunction()',100);
}
}
}
myText.onkeyup = function(e)
{
keyIs = "up";
}

If you don't care about supporting Opera, this is easy:
textbox.onkeydown = function(e)
{
if (e.keyCode == 38)
{
incrementTextBox();
}
}
However, Opera doesn't fire keydown for key repeats... you'll have to mimic that by calling incrementTextBox() at an interval, and stopping when the key is lifted. I tested this in WebKit (Chrome 6.0), FF3, Opera 10.6, IE7, IE8, IE9, even IE Quirks:
var textbox = null;
window.onload = function()
{
var timeoutId = null;
var intervalId = null;
var incrementRepeatStarted = false;
function startIncrementKeyRepeat()
{
timeoutId = window.setTimeout(function()
{
intervalId = window.setInterval(incrementTextBox, 50);
}, 300);
}
function abortIncrementKeyRepeat()
{
window.clearTimeout(timeoutId);
window.clearInterval(intervalId);
timeoutId = null;
intervalId = null;
}
function endIncrementKeyRepeat()
{
abortIncrementKeyRepeat();
incrementRepeatStarted = false;
}
textbox = document.getElementById("incrementer");
textbox.onkeydown = function(e)
{
e = e || window.event;
if (e.keyCode == 38)
{
if (!incrementRepeatStarted)
{
startIncrementKeyRepeat();
incrementRepeatStarted = true;
}
else if (timeoutId || intervalId)
{
abortIncrementKeyRepeat();
}
incrementTextBox();
}
else if (incrementRepeatStarted)
{
endIncrementKeyRepeat();
}
}
textbox.onkeyup = endIncrementKeyRepeat;
}
function incrementTextBox()
{
var val = parseInt(textbox.value) || 0;
val++;
textbox.value = val;
}

I wanted to do this, i just used input field with type="number"

Related

How to check if escape key has been pressed 3 times (like the trevor project website's safety)

I've been trying to make a website for people that feel their life is in danger or anything like that. I'm trying to recreate the Trevor Project's escape key function with javascript.
I have some base code but it's not working:
window.addEventListener("keydown", checkKeyPressed, false);
var escTime = 0;
function checkKeyPressed(evt) {
if (evt.keyCode === "27") {
window.clearTimeout();
escTime++;
window.setTimeout(function(){
escTime = 0;
}, 1000);
}
if (escTime == 3) {
window.location.replace("https://classroom.google.com/h");
escTime = 0;
}
}
I'd say you're fairly close, but:
You have to remember the handle from setTimeout in order to cancel it, because you have to give it to clearTimeout.
keyCode is deprecated (though unlikely to actually go away), look at key and code instead.
There's no point in assigning 0 back to escTime, the treplace` leaves the page anyway.
So perhaps:
window.addEventListener("keydown", checkKeyPressed, false);
let escapeTimerHandle = 0;
let escapeCount = 0;
function checkKeyPressed(evt) {
if (evt.key === "Escape" || evt.key === "Esc") {
clearTimeout(escapeTimerHandle);
escapeCount++;
if (escapeCount == 3) {
window.location.replace("https://classroom.google.com/h");
} else {
escapeTimerHandle = setTimeout(function(){
escapeCount = 0;
}, 1000);
}
}
}
You can accomplish this using a closure:
function createCheckKeyPressFunction()
{
let timeout;
let escTime = 0;
function checkKeyPressed(evt)
{
if (evt.key === "Escape")
{
console.log("Escape Detected");
window.clearTimeout(timeout);
escTime += 1;
timeout = window.setTimeout(()=>
{
escTime = 0;
console.log("Escape count reset to zero, due to timeout.");
}, 1000);
}
if (escTime === 3) {
let url = "https://classroom.google.com/h";
console.log(url);
window.location.replace(url);
escTime = 0;
}
}
return checkKeyPressed;
}
let checkKeyPressed = createCheckKeyPressFunction();
window.addEventListener("keydown", checkKeyPressed, false);
<p>Click to give this embedded snippet focus, and then test by hitting the ESC key.</p>
Since the code snippet (above) is embedded in this page, be sure to click into it after running it (to give it focus) before testing it with the Esc key.

JS Function self-disable for a specific time after execution

I'm trying to create a function which is executed by a keypress and disabled for a specific time after execution.
function do_something() {
console.log('lorem ipsum');
}
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
}
}
Is there any way to disable it for (let's say) 2 seconds after every execution?
Yes, there is a way: use a Timeout to temporally set a boolean to certain value and then check it's value before calling do_something().
Example:
let cooldown = false;
const RECHARGE_TIME = 2000; //ms
function do_something() {
console.log('lorem ipsum');
}
document.onkeypress = function(e) {
if (!cooldown && e.keyCode == '32') {
do_something();
startCooldown();
}
}
function startCooldown() {
cooldown = true;
setTimeout (function(){ cooldown = false}, RECHARGE_TIME);
}
EDIT: as Mosè Raguzzini noted: Depending on how important accuracy is, maybe this isn't the best method, since (as you can see here) it can be inacurate.
Try that, is a very simple and straightforward solution:
var firstExecution = 0; // Store the first execution time
var interval = 2000; // 2 seconds
function do_something() {
// current date
var date = new Date();
var milliseconds = date.getTime();
if((milliseconds - firstExecution) > interval){
firstExecution = milliseconds;
console.log('lorem ipsum');
} else {
console.log('too early');
}
}
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
}
}
A very silly answer would be to sleep javascript execution for a specific time.
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Then
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
sleep(2000);
}
}
I said silly because it stop your entire script for a specific time, you may not need that behavior!
Some thing like that, execution will be disable for 5s
var lastClicked = 0;
document.onkeypress = function(e) {
var now = new Date();
if (now - lastClicked > 5000) { //set a 5s delay
lastClicked = now;
if (e.keyCode == '32') {
do_something();
}
}
}
function do_something() {
console.log('lorem ipsum');
}
var timeout = false; //Control variable
var miliseconds = 2000; //Time in miliseconds for the function to enable again
function do_something() {
if(timeout) return alert("Function disabled");
console.log('lorem ipsum');
timeout = true;
setTimeout(function() { timeout = false }, miliseconds);
}
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
}
}
Lodash has throttle for this purpose.

Detect multiple keypresses on Firefox (Greasemonkey)

So I'm trying to be able to trigger a script using a combinations of keypresses.
var down = {
};
$(document).chardown(function (e) {
down[e.charCode] = true;
}).charup(function (e) {
if (down[68] && down[69] && down[86]) {
var nextButton = document.getElementsByClassName('button-next') [0];
nextButton.click();
}
down[e.keyCode] = false;
});
This is the code I've got so far. So the intention is (afaik) to trigger the
var nextButton = document.getElementsByClassName('button-next') [0];
nextButton.click();
When I press e+d+v. But it isn't working. And if I only use the above part it keeps changing episode (Obvioulsy).
I didn't find any documentation related to chardown and charup in jquery or greasemonkey.I think you were trying to use keydown and keup. You should replace charCode with keyCode.
var down = {};
$(document).keydown(function (e) {
down[e.keyCode] = true;
}).keyup(function (e) {
if (down[68] && down[69] && down[86]) {
alert("Hello");
}
down[e.keyCode] = false;
});

Using a onKeyDown event with CharCode

I'm making my own player with drumpad and i need help to assign functions to keyboard keys. I've got playlist with (now) 3 sounds:
var playlist = [
{
artist: "Snare",
title: "Snare",
source: "Snare.wav"
},
{
artist: "Kick",
title: "Kick",
source: "Kick.wav"
},
{
artist: "Clap",
title: "Clap",
source: "Clap.wav"
},
];
I've got some functions which i'm running by buttons:
var currentSong = 0;
var play = function() {
var audio = document.getElementById("audio1");
audio.play();
}
var pause = function() {
var audio = document.getElementById("audio1");
audio.pause();
}
var jeden = function() {
var audio = document.getElementById("audio1");
currentSong = 0;
audio.src = playlist[currentSong].source;
}
var dwa = function() {
var audio = document.getElementById("audio1");
currentSong = 1;
audio.src = playlist[currentSong].source;
}
var trzy = function() {
var audio = document.getElementById("audio1");
currentSong = 2;
audio.src = playlist[currentSong].source;
}
And the html:
<body>
<audio autoplay="autoplay" ontimeupdate="showinfo()" id="audio1"
controls="controls"></audio>
<br/>
<button onclick="jeden()">1</button>
<button onclick="dwa()">2</button>
<button onclick="trzy()">3</button>
</body>
I think the essiest way is to assign buttons to keyboard keys. Anybody can help me?
dzień dobry
The code will be something like this. You can change keypress() to keyup() or keydown() if suitable - check the documentation of those functions to appreciate the differences.
$('body').keypress(function( event ) {
if ( event.which == 49 ) {
jeden();
}
});
I referred to this page to determine the number 49 means key 1:
https://css-tricks.com/snippets/javascript/javascript-keycodes/
I should mention this is a jQuery solution and you will need to learn some basic jQuery setup. It is a popular approach to solving this problem. You will also be able to use jQuery to do your existing stuff a much nicer way.
Here is an example. https://jsfiddle.net/7j0krzx5/
use this
$(document ).on( "keydown", function(event) {
if (event.which === 80) // P key
{
event.preventDefault();
// do something e.g
}
else if (event.which === 78) // N key
{
event.preventDefault();
// do something
}
// console.log(event.which);
});
JSFiddle example
If you don't want to use jquery
var play = function() {
alert("Play");
}
var next = function() {
alert("Next");
}
function keyDownListener(event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(keyCode === 80){ // P key
event.preventDefault();
play()
}
else if (keyCode == 78 ) { // N key
event.preventDefault();
next();
}
}
document.addEventListener("keydown", keyDownListener, false);
JSFiddle example

How to detect a long touch pressure with javascript for android and iphone?

How to detect a long touch pressure with javascript for android and iphone?
native javascript or jquery...
I want something that sound like :
<input type='button' onLongTouch='myFunc();' />
The problem with using Touch End to detect the long touch is it won't work if you want the event to fire after a certain period of time. It is better to use a timer on touch start and clear the event timer on touch end. The following pattern can be used:
var onlongtouch;
var timer;
var touchduration = 500; //length of time we want the user to touch before we do something
touchstart() {
timer = setTimeout(onlongtouch, touchduration);
}
touchend() {
//stops short touches from firing the event
if (timer)
clearTimeout(timer); // clearTimeout, not cleartimeout..
}
onlongtouch = function() { //do something };
Here is an extended version of Joshua answer, as his code works well till user doesn't perform multitouch (you can tap screen with two fingers and function will be triggered two times, 4 fingers - 4 times).
After some additional test scenarios I even triggered possibility to touch very freequently and receive function executing after each tap.
I added variable named 'lockTimer' which should lock any additional touchstarts before user trigger 'touchend'.
var onlongtouch;
var timer;
var touchduration = 800; //length of time we want the user to touch before we do something
function touchstart(e) {
e.preventDefault();
if (!timer) {
timer = setTimeout(onlongtouch, touchduration);
}
}
function touchend() {
//stops short touches from firing the event
if (timer) {
clearTimeout(timer);
timer = null;
}
}
onlongtouch = function() {
timer = null;
document.getElementById('ping').innerText+='ping\n';
};
document.addEventListener("DOMContentLoaded", function(event) {
window.addEventListener("touchstart", touchstart, false);
window.addEventListener("touchend", touchend, false);
});
<div id="ping"></div>
The solutions posted here ignore the fact that the user needs to touch the screen to initiate scroll. We only want the long-press behavior if the user is not trying to scroll.
function onLongPress(element, callback) {
let timer;
element.addEventListener('touchstart', () => {
timer = setTimeout(() => {
timer = null;
callback();
}, 500);
});
function cancel() {
clearTimeout(timer);
}
element.addEventListener('touchend', cancel);
element.addEventListener('touchmove', cancel);
}
And then:
onLongPress(element, () => {
console.log('Long pressed', element);
});
I've done it this way in my Android app:
registered events listeners:
var touchStartTimeStamp = 0;
var touchEndTimeStamp = 0;
window.addEventListener('touchstart', onTouchStart,false);
window.addEventListener('touchend', onTouchEnd,false);
added functions:
var timer;
function onTouchStart(e) {
touchStartTimeStamp = e.timeStamp;
}
function onTouchEnd(e) {
touchEndTimeStamp = e.timeStamp;
console.log(touchEndTimeStamp - touchStartTimeStamp);// in miliseconds
}
checked time difference and did my stuff
I hope this will help.
Building on the solution by #djanowski to handle touch scroll. This should also prevent context menu and selection on long press.
function onLongPress(element, callback) {
var timeoutId;
element.addEventListener('touchstart', function(e) {
timeoutId = setTimeout(function() {
timeoutId = null;
e.stopPropagation();
callback(e.target);
}, 500);
});
element.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
element.addEventListener('touchend', function () {
if (timeoutId) clearTimeout(timeoutId);
});
element.addEventListener('touchmove', function () {
if (timeoutId) clearTimeout(timeoutId);
});
}
onLongPress(document.getElementById('kitty1'), function(element) {
alert('Meow from ' + element.outerHTML );
});
onLongPress(document.getElementById('kitty2'), function(element) {
alert('Meow from ' + element.outerHTML );
});
img {
max-width: 100%;
-webkit-user-select: none; /* Safari */
-ms-user-select: none; /* IE 10 and IE 11 */
user-select: none; /* Standard syntax */
}
<p>Long press on kitty! Kitty should meow on 500ms long press but not scroll</p>
<img id="kitty1" src="http://placekitten.com/300/400" />
<img id="kitty2" src="http://placekitten.com/300/300" />
We can calculate the time difference when the touch started and when the touch end. If the calculated time difference exceed the touch duration then we use a function name taphold.
var touchduration = 300;
var timerInterval;
function timer(interval) {
interval--;
if (interval >= 0) {
timerInterval = setTimeout(function() {
timer(interval);
});
} else {
taphold();
}
}
function touchstart() {
timer(touchduration);
}
function touchend() {
clearTimeout(timerInterval);
}
function taphold(){
alert("taphold");
}
document.getElementById("xyz").addEventListener('touchstart',touchstart);
document.getElementById("xyz").addEventListener('touchend',touchend);
For cross platform developers:
Mouseup/down seemed to work okay on android - but not all devices ie (samsung tab4). Did not work at all on iOS.
Further research its seems that this is due to the element having selection and the native magnification interupts the listener.
This event listener enables a thumbnail image to be opened in a bootstrap modal, if the user holds the image for 500ms.
It uses a responsive image class therefore showing a larger version of the image.
This piece of code has been fully tested upon (iPad/Tab4/TabA/Galaxy4):
var pressTimer;
$(".thumbnail").on('touchend', function (e) {
clearTimeout(pressTimer);
}).on('touchstart', function (e) {
var target = $(e.currentTarget);
var imagePath = target.find('img').attr('src');
var title = target.find('.myCaption:visible').first().text();
$('#dds-modal-title').text(title);
$('#dds-modal-img').attr('src', imagePath);
// Set timeout
pressTimer = window.setTimeout(function () {
$('#dds-modal').modal('show');
}, 500)
});
This better solution based on #Joshua, sometimes the code need to be called directly inside event (some web API require user acction to trigger something) for this case you can use this modification:
var longtouch;
var timer;
//length of time we want the user to touch before we do something
var touchduration = 500;
function touchstart() {
longtouch = false;
timer = setTimeout(function() {
longtouch = true;
timer = null
}, touchduration);
}
function touchend() {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (longtouch) {
// your long acction inside event
longtouch = false;
}
}
in setTimeout you set the flag to true and inside touchend, you check if it was set.
This worked for my use-case i.e wanted to execute certain function for the time screen is touched.
let triggerInterval = 200; // in milliseconds
let timerId;
function touchstart(e) {
// e.preventDefault();
timerId = setInterval(yourFunction, triggerInterval);
}
function touchend(e) {
clearInterval(timerId);
}
function yourFunction() {
// perform your logic
}
document.addEventListener("touchstart", touchstart);
document.addEventListener("touchend", touchend);
Note:- Smaller value in triggerInterval will execute yourFunction() more faster.
When you are done with your program, then you can remove the respective event Listeners:
document.removeEventListener("touchstart", touchstart);
document.removeEventListener("touchend", touchend);
Long tap event that working in all browser
(function (a) {
function n(b) { a.each("touchstart touchmove touchend touchcancel".split(/ /), function (d, e) { b.addEventListener(e, function () { a(b).trigger(e) }, false) }); return a(b) } function j(b) { function d() { a(e).data(h, true); b.type = f; jQuery.event.handle.apply(e, o) } if (!a(this).data(g)) { var e = this, o = arguments; a(this).data(h, false).data(g, setTimeout(d, a(this).data(i) || a.longclick.duration)) } } function k() { a(this).data(g, clearTimeout(a(this).data(g)) || null) } function l(b) {
if (a(this).data(h)) return b.stopImmediatePropagation() ||
false
} var p = a.fn.click; a.fn.click = function (b, d) { if (!d) return p.apply(this, arguments); return a(this).data(i, b || null).bind(f, d) }; a.fn.longclick = function () { var b = [].splice.call(arguments, 0), d = b.pop(); b = b.pop(); var e = a(this).data(i, b || null); return d ? e.click(b, d) : e.trigger(f) }; a.longclick = { duration: 500 }; a.event.special.longclick = {
setup: function () {
/iphone|ipad|ipod/i.test(navigator.userAgent) ? n(this).bind(q, j).bind([r, s, t].join(" "), k).bind(m, l).css({ WebkitUserSelect: "none" }) : a(this).bind(u, j).bind([v,
w, x, y].join(" "), k).bind(m, l)
}, teardown: function () { a(this).unbind(c) }
}; var f = "longclick", c = "." + f, u = "mousedown" + c, m = "click" + c, v = "mousemove" + c, w = "mouseup" + c, x = "mouseout" + c, y = "contextmenu" + c, q = "touchstart" + c, r = "touchend" + c, s = "touchmove" + c, t = "touchcancel" + c, i = "duration" + c, g = "timer" + c, h = "fired" + c
})(jQuery);
Bind longclick event with time interval
$('element').longclick(250, longClickHandler);
below function fire on Long Tap on touch device
function longClickHandler() {
alter('Long tap Fired');
}

Categories

Resources