javascript shortcut key / stop Interval function - javascript

i make a shortcut key for javascript function . i set the S key for start this and i so set the Z key for clear Interval function but im tired about this and when press Z key the Interval doesnt stop :(
var isCtrl = false;
document.onkeydown=function(e){
if(e.which == 83) {
var elem = document.elementFromPoint( cursorX,cursorY );
elem.addEventListener('click', function() {
console.log('clicked')
}, false);
var support = true;
try {
if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
support = false;
} else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
support = false;
}
} catch (e) {
support = false;
}
var refreshIntervalId = setInterval(function() {
if (support) {
var event = new MouseEvent('click');
}else{
var event = document.createEvent('Event');
event.initEvent('click', true, true);
}
elem.dispatchEvent(event);
},10);
var cursorX;
var cursorY;
cursorX = 0; cursorY = 0;
document.onmousemove = function(e){
cursorX = e.clientX;
cursorY = e.clientY;
elem = document.elementFromPoint(e.clientX, e.clientY);
}
if(e.which == 90) {
clearInterval(refreshIntervalId);
}
}
}
help me i want to press Z key and Interval stop but i can`t ...
UPDATE : this code work correctly . use S key for start and Z key for stop the function .
var elem = document.elementFromPoint( cursorX,cursorY );
elem.addEventListener('click', function() {
console.log('clicked')
}, false);
var support = true;
try {
if (new MouseEvent('click', {bubbles: false}).bubbles !== false) {
support = false;
} else if (new MouseEvent('click', {bubbles: true}).bubbles !== true) {
support = false;
}
} catch (e) {
support = false;
}
var cursorX;
var cursorY;
cursorX = 0; cursorY = 0;
document.onmousemove = function(e){
cursorX = e.clientX;
cursorY = e.clientY;
elem = document.elementFromPoint(e.clientX, e.clientY);
}
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
if (support) {
var event = new MouseEvent('click');
}else{
var event = document.createEvent('Event');
event.initEvent('click', true, true);
}
elem.dispatchEvent(event);
},1000);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}

You also have to code it in a way to avoid starting the timer more than once. You should construct it more like this (move the var for the timer outside the function):
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
// code...
},10);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}

You doesn't seem to make an event to listen to keypress.
jQuery:
$(window).keypress(function(e) {
if (e.which == 90) {
clearInterval(refreshIntervalId);
}
});
Vanilla JS:
var keyEvent = function (e) {
if (e.which == 90) {
clearInterval(refreshIntervalId);
}
};
window.addEventListener('keypress', keyEvent);

Related

Preparing for main Click and Touch Events

Trying to get the following code to work, a working example presented in jsfiddle will help. The codes for a game that should work on both click hardware and touchscreen hardware.
If there's a way to avoid using an init function that seems to help. Unless you feel like adding an example of how to get a draw function call into the mix somehow.
<p id="Xpos"></p>
<p id="Ypos"></p>
<script>
//############################### Mouse and Touch Events : Start
<!-- Source Code Web Site:
http://blog.patricktresp.de/2012/02/
internet-explorer-8-
and-all-the-fun-stuff-e-stoppropagation-e-preventdefault-mousedown/ -->
var el;
el = document.getElementById('bgLayerMain');
if( el.addEventListener )
{
el.addEventListener('mousedown', onMouseDown, false);
}else if( el.attachEvent ) {
el.attachEvent('onmousedown', onMouseDown);
}
if( is_touch_device() ) {addListeners(); alert("here");}
function stopEvent(e) {
if(!e) var e = window.event;
//e.cancelBubble is supported by IE -
// this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
//e.stopPropagation works only in Firefox.
if ( e.stopPropagation ) e.stopPropagation();
if ( e.preventDefault ) e.preventDefault();
return false;
}
function addListeners( el )
{// Allow function call without passing parameters
var e = el;
if( !e ) e = document.getElementById('bgLayerMain');
var el = e;
if( el )
{
if( el.addEventListener )
{
el.addEventListener('mouseup', onMouseUp, true);
el.addEventListener('mousemove', onMouseMove, true);
el.addEventListener('touchstart', onTouchStart, true);
el.addEventListener('touchmove', onTouchMove, true);
el.addEventListener('touchend', onTouchEnd, true);
}else if( el.attachEvent ) {
// make sure mouse events have the prefix <strong>on</strong>
el.attachEvent('onmouseup', onMouseUp);
el.attachEvent('onmousemove', onMouseMove);
el.attachEvent('touchstart', onTouchStart);
el.attachEvent('touchmove', onTouchMove);
el.attachEvent('touchend', onTouchEnd);
}
}
}
// also remove the Listeners correctly:
function removeListeners( el ) {
var e = el;
if( !e ) e = document.getElementById('bgLayerMain');
var el = e;
if( el )
{
if( el.removeEventListener )
{
el.removeEventListener('mouseup', onMouseUp);
el.removeEventListener('mousemove', onMouseMove);
el.removeEventListener('touchstart', onTouchStart);
el.removeEventListener('touchmove', onTouchMove);
el.removeEventListener('touchend', onTouchEnd);
}else if( el.detachEvent ) {
el.detachEvent('onmouseup', onMouseUp);
el.detachEvent('onmousemove', onMouseMove);
el.detachEvent('touchstart', onTouchStart);
el.detachEvent('touchmove', onTouchMove);
el.detachEvent('touchend', onTouchEnd);
}
}
}
function onMouseDown(e) {
log('-> mouse down');
addListeners();
e.touches = [{clientX: e.clientX, clientY: e.clientY}];
onTouchStart(e);
stopEvent(e);
}
function onTouchStart(e) {
log('-> touch start');
//do something with e.touches[0].clientX or e.touches[0].clientY
updateMousePos(e.touches[0].clientX,e.touches[0].clientY);
stopEvent(e);
}
function onMouseMove(e) {
log('-> mouse move');
e.touches = [{clientX: e.clientX, clientY: e.clientY}];
onTouchMove(e);
stopEvent(e);
}
function onTouchMove(e) {
log('-> touch move');
//do something with e.touches[0].clientX or e.touches[0].clientY
updateMousePos(e.touches[0].clientX,e.touches[0].clientY);
stopEvent(e);
}
function onMouseUp(e) {
log('-> mouse up');
e.touches = [{clientX: e.clientX, clientY: e.clientY}];
removeListeners();
stopEvent(e);
}
function onTouchEnd(e) {
log('-> touch end');
if( !is_touch_device() ) removeListeners();
}
function log(str) {
var c;
c = document.getElementById('console');
c.innerHTML = str + '
' + c.innerHTML;
}
function is_touch_device() {
return !!('ontouchstart' in window) ? 1 : 0;
}
function updateMousePos(){
//update posX and posY
}
//############################### Mouse and Touch Events : End
Simplified it to the following, perhaps a better way, yet for now works for me.
var clickOrTouchActive = 0;
addEventListener("mousedown", onClickOrTouchStart, false);
addEventListener("touchstart", onClickOrTouchStart, false);
addEventListener("mousemove", onClickOrTouchMove, false);
addEventListener("touchmove", onClickOrTouchMove, false);
addEventListener("mouseup", onClickOrTouchEnd, false);
addEventListener("touchend", onClickOrTouchEnd, false);
function onClickOrTouchStart(e) {
updateMousePos(e.pageX,e.pageY);
tileMouseClicked(e.pageX,e.pageY);
fAngleOfMotion(e.pageX,e.pageY);
clickOrTouchActive = 1;
e.preventDefault();
return false;
}// end function onClickOrTouchStart
function onClickOrTouchMove(e) {
if (clickOrTouchActive == 1){
updateMousePos(e.pageX,e.pageY);
tileMouseClicked(e.pageX,e.pageY);
fAngleOfMotion(e.pageX,e.pageY);
}
e.preventDefault();
return false;
}//end function onClickOrTouchMove
function onClickOrTouchEnd(e) {
updateMousePos(e.pageX,e.pageY);
tileMouseClicked(e.pageX,e.pageY);
fAngleOfMotion(e.pageX,e.pageY);
clickOrTouchActive = 0;
e.preventDefault();
return false;
}// end function onClickOrTouchEnd

Javascript setTimeout not working | onkeydown

what I'm trying to do is when you hold w or s it should call function every second. But right now it only delays first call then it makes like 12 calls every second. Thanks in advance for anybody who will answer. I you want mor infos just ask.
<!DOCTYPE html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function call(direction) {
$.ajax({ url: '/' + direction });
}
</script>
<script>
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W") {
direction = 'down';
} else if (key_press == "S") {
direction = 'up';
}
var update = setTimeout(function () {
call(direction)
}, 250);
}
document.onkeyup = function (event) {
clearTimeout(update);
}
</script>
Use setInterval instead of setTimeout. Also consider update as global var.
var update = '';
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W") {
direction = 'down';
} else if (key_press == "S") {
direction = 'up';
}
if (!update) {
update = setInterval(function () {
call(direction)
}, 1000);
}
}
document.onkeyup = function (event) {
clearInterval(update);
update = '';
}
tri this
$(document).ready(function(){
$(document).on('keydown',function(e){
// content
});
});
<script type="text/javascript">
function call(direction) {
$.ajax({ url: '/' + direction });
}
var update, direction, key = null;
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W" && key != "W") {
key = "W";
direction = 'down';
update = setInterval(function () { call(direction); }, 1000);
} else if (key_press == "S" && key != "S") {
direction = 'up';
key = "S";
update = setInterval(function () { call(direction); }, 1000);
}
}
document.onkeyup = function (event) {
clearInterval(update);
}
</script>
It is something close to how a debounce function works, here's my attempt to solve your question:
function debounce(callback, ms){
var timeOutId;
window.addEventListener('keydown', function(evt){
var key = String.fromCharCode(evt.keyCode);
if(['W','S'].indexOf(key) !== -1 && !timeOutId){
timeOutId = setTimeout(function(){
callback(evt);
timeOutId = null;
}, ms);
}
});
window.addEventListener('keyup', function(evt){
clearTimeout(timeOutId);
});
}
debounce(function(){ /* your function */}, 1000);
Demo on JSFiddle.

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

Clearing setTimeout issues

I'm trying to set "mouseactive" to true less than a second after a key command, but I would like to cancel that action if the key is pressed within that time period. However I can't seem to figure out how to do this. This is what I have...
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
var t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
var t = setTimeout("mouseActive()",800);
}
});
function mouseActive() {
mouseactive = true;
}
But this doesn't work, it doesn't set mouseactive back to true... can anyone tell me what I'm doing wrong here?
Edit: Cleaned up redundant code.
More Edits: Make sure your var t is defined outside any closure including $(document).ready. See below,
var t = null;
$(document).ready(function () {
//..below code except for var t = null
});
Declare var t outside the handler.
var t = null;
$(window).keydown(function(e) {
e.preventDefault();
if (e.keyCode == 40) {
mouseactive = false;
} else if (e.keyCode == 38) {
mouseactive = false;
}
if (t != null) clearTimeout(t);
t = setTimeout(mouseActive, 800);
});
function mouseActive() {
mouseactive = true;
}
Your problem is that t is not in scope the 2nd time the function runs. You need to make t a global variable .
var t;
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
t = setTimeout(mouseActive,800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
t = setTimeout(mouseActive,800);
}
});
function mouseActive() {
mouseactive = true;
}
P.S. Don't pass strings to setTimeout, pass functions. It uses eval when you pass strings.
you are redeclaring "t" all the time, try this:
var t = null;
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
if(t != null)
{
clearTimeout(t);
}
t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
if(t != null)
{
clearTimeout(t);
}
t = setTimeout("mouseActive()",800);
}
});
function mouseActive() {
mouseactive = true;
}

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

Categories

Resources