I'm trying to do two different actions when the canvas is clicked and when a key is pressed, but it seems like both can't be done at the same time. Is there a way to do this even if the functions are completely unrelated?
canv.onmousedown = function() {
console.log("Hello World");
};
And for keypress...
if(rightPressed && heroX < canvas.width) {
heroX += heroSpeed;
}
It can be done with single function. Listen for click event on canvas and check if it goes along with, for example shift being pressed.
function(e) {
if(!e.shiftKey) return; //it will do nothing unless shift key was pressed
}
You can do it for any button with e.keyCode property. For example e.keyCode === 32 would check if spacebar was pressed during the event. You can check any keyCode here.
Related
I am trying to create a hangman game, but my event listener doesn't seem as though it's working? When I press a key, there's no response from the webpage.
document.onkeydown = function (event) {
// If the game is finished, one keystroke will reset the game
if (hasFinished) {
resetGame();
hasFinished = false;
console.log("eventListenerWorking16");
} else {
// Make sure A-Z was actually pressed
if (event.keyCode >= 65 && event.keycode <= 90) {
makeGuess(event.key.toLowerCase());
updateDisplay();
checkWin();
checkLoss();
console.log("eventListenerWorking16");
}
}
};
Oh great .. One typo can takes hrs to resolve
One typo in this line
if (event.keyCode >= 65 && event.keycode <= 90) {
It has to be event.keyCode Caps not small
IMHO the event should fire correctly.
I think to make a better debug you should place a console.log right after the anonymous function call (see code below).
This way it will be possible to understand if there is something wrong after (that concerns the logic applied later).
document.onkeydown = function (event) {
console.log("keydown event fired");
// If the game is finished, one keystroke will reset the game
if (hasFinished) {
resetGame();
hasFinished = false;
console.log("eventListenerWorking16 hasFinished");
} else {
// Make sure A-Z was actually pressed
if (event.keyCode >= 65 && event.keycode <= 90) {
makeGuess(event.key.toLowerCase());
updateDisplay();
checkWin();
checkLoss();
console.log("eventListenerWorking16 makeGuess");
}
}
};
Try using this code:
document.addEventListener("keydown", myScript);
I am trying to make a program using Processing JS that draws a space ship and then allows the user to control it using left and right arrows to turn it and z to make it accelerate. I have been using the keyIsPressed function like so
keyIsPressed = function(){
if(keyCode === 90){
println("OK");
ship.accelerate();
}
};
but the ship does not move and nothing gets printed in by the println(); when I press z so it must not be activating the function. Does anyone know how to fix this? here is a link to the full code https://www.khanacademy.org/computer-programming/spin-off-of-project-asteroids-spaceship/4635808988463104.
Basically, keyIsPressed is a boolean value that is true when the user is pressing any button on the keyboard and false when there is no keys pressed. Basically,
var draw = function(){
if (keyIsPressed && keyCode === 90){
ship.accelerate();
}
}
The keyIsPressed variable is a boolean value that's true whenever a key is pressed.
If you want a function, you should use the keyPressed() function, and you should not specify it inside draw(). It should be at the same level as draw().
Also, you used ship.accerate(), which isn't a function. You probably meant ship.accelerate() instead.
Putting all of that together, it looks like this:
draw= function() {
background(161, 159, 159);
ship.update();
ship.display();
println(ship.position.x);
};
keyPressed = function(){
if(keyCode === 90){
ship.accelerate();
}
};
For functions it is keyPressed, no keyIsPressed.
keyPressed = function(){
if(keyCode === 90){
println("OK");
ship.accelerate();
}
};
I am designing a keyboard interface through javascript, and I want to define keystroke combinations, like shift+rightkey or ctrl+tab. But after tinkering with javascript, as seen here, I've noticed that all keyevents are interrupting. In the provided example, if you go to hit the shiftkey while holding down the rightkey, the functionality of the rightkey is interrupted!
v = 1; /*v is the variable of velocity.*/
window.addEventListener("keydown", function(event)
{
if(event.keyCode == 39) /*39 is the keycode of rightarrowkey.*/
{
//moves an element by the velocity.
var keystroke = document.getElementById("keystroke");
keystroke.style.left = parseInt(keystroke.style.left.slice(0,-2))+v+"px";
}
if(event.keyCode == 16) /*16 is the keycode of shift.*/
{
//increases the velocity of the element by four.
document.getElementById("keystroke").style.borderColor = "red";
v = 4;
}
}, false); //but hitting the shiftkey while hitting the rightkey interrupts..!
I also experimented with recording all keystrokes through an object which is then iterated through at a designated interval for defined keystrokes, as seen here. But this system of handling the keyboard doesn't preserve the individual keystrokes; if I hit a key too fast, it may not be considered, or if I hold a key for too long, it may be overconsidered!
After giving it a bit of thought, I may have figured out a method to both preserve each keystroke while handling interrupting keyevents. My code is somewhat quirky, but it works well for managing the keystrokes from the users.
The solution to handling each keystroke without interruptions was through registering each keyevent within an object, as was previously suggested in my question. The code continually iterates through this object to handle any new keyevents.
But to ensure each keystroke is preserved and handled at least once, a keybinding must be registered for each keyevent. I expanded the scripting for the object to register both keystrokes as well as keybindings.
var kbdin =
{
stroked: new Object(),
upbinded: new Object(),
downbinded: new Object(),
downbindKeystroke: function(keycode, functionality) {this.downbinded[keycode] = functionality;},
upbindKeystroke: function(keycode, functionality) {this.upbinded[keycode] = functionality;},
isDownbinded: function(keycode) {return this.downbinded[keycode];},
isUpbinded: function(keycode) {return this.upbinded[keycode];},
isStroked: function(keycode) {return this.stroked[keycode];},
onDownstroke: function(event)
{
var keycode = event.keyCode;
if(!this.isStroked(keycode))
{
this.stroked[keycode] = 1;
if(this.isDownbinded(keycode))
{this.downbinded[keycode]();}
}
if(this.isDownbinded(keycode))
{event.preventDefault();}
},
onUpstroke: function(event)
{
var keycode = event.keyCode;
delete this.stroked[keycode];
if(this.isUpbinded(keycode))
{
this.upbinded[keycode]();
event.preventDefault();
}
},
handleKeystrokes: function()
{
for(var keycode in this.downbinded)
{
if(this.isStroked(keycode) > 5)
{this.downbinded[keycode]();}
}
for(var keycode in this.stroked)
{this.stroked[keycode]++;}
}
};
document.addEventListener("keyup", function(event) {kbdin.onUpstroke(event);}, false);
document.addEventListener("keydown", function(event) {kbdin.onDownstroke(event);}, false);
window.setInterval(function() {kbdin.handleKeystrokes();}, 50);
Now both the keystrokes and keybindings are coupled together, supporting each keyevent with the functionality to both signal a keystroke and execute a keybinding. It may be a bit quirky, but this code handles noninterrupting keyevents while still preserving individual keystrokes!
This involves HTML + JS and/or JQuery:
I would have commented on the previous post, but I don't have comment reputation or cannot comment for some reason.
Josh Stodola's great code from Part I is as follows:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
This works great except .replace puts the cursor at the end of the string on every keyup (at least in IE8 and Chrome).
As a result, it renders the left & right cursor keys useless, which is needed inside the input box.
Is there any way to enhance the above code so that the cursor keys do not activate it, but so that the text still gets updated on the fly?
The best solution is to avoid using key events to capture text input. They're not the best tool for the job. Instead, you should use the HTML5 oninput event (supported in the latest and recent versions of every current major browser) and fall back to onpropertychange for older versions of Internet Explorer:
var alreadyHandled;
txt.bind("input propertychange", function (evt) {
// return if the value hasn't changed or we've already handled oninput
if (evt.type == "propertychange" && (window.event.propertyName != "value"
|| alreadyHandled)) {
alreadyHandled = false;
return;
}
alreadyHandled = true;
// Your code here
});
These events don't fire for keys that don't result in text entry — don't you just hate it when you shift-tab back to a form element and the resulting keyup event causes the page's script to move focus forward again?
Additional benefits over key events:
They fire immediately when the key is pressed and not when the key is lifted, as in keyup. This means you don't get a visual delay before any adjustments to the text are made.
They capture other forms of text input like dragging & droppping, spell checker corrections and cut/pasting.
Further reading at Effectively detecting user input in JavaScript.
Update the function:
var func = function(e) {
if(e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40){
txt.val(txt.val().replace(/\s/g, ''));
}
}
try:
$(function() {
var txt = $("#myTextbox");
var func = function(e) {
if(e.keyCode != "37" && e.keyCode != "38" && e.keyCode != "39" && e.keyCode != "40"){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(function(evt){
if(evt.keyCode < 37 || evt.keyCode > 40) {
func;
}
}).blur(func);
});
Something like that should do it. It will run the function if the keycode isn't 37,38,39 or 40 (the four arrow key keycodes). Note that it won't actually stop the cursor position moving to the end when any other key is pressed. For that, you'd need to keep track of the current cursor position. Take a look at this link for jCaret plugin, which can do this
Is there a way in js/jQuery how to have these two combinations of keypresses?
ESCape key
and
SHIFT + ESCape key
when I implemented it using:
document.onkeydown = function(e){if (e == null) {keycode = event.keyCode;}
else {keycode = e.which;}
if(keycode == 27){closeAll();}}
//upon pressing shift + esc
$(document).bind('keypress',function(event)
{
if(event.which === 27 && event.shiftKey)
{
closetogether();
}
});
The escape button works perfectly but the one with the shift + esc is getting confused I think because it's doing nothing. Don't worry the function works as when I change the combining key 27 to 90 (z) for example it works just fine.
Can someone opt me for a better way ?
Why don't you bind the keydown event using jQuery? That way you would already have a normalized event variable. You can also check the status of the shift key in the same handler.
These events send different keycodes back. Use keyup/keydown for capturing certain keys by scancodes and use keypress to capture actual text input by characters.
$(document).bind('keydown', function(event) {
if(event.which === 27){
if(event.shiftKey){
closetogether();
} else {
closeAll();
}
}
});