How to detect click+specific key press in javaScript? - javascript

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.

Related

Executing Different Parts of JavaScript Code by Pressing Key and Clicking

I have code for 3 different task which I want to execute by clicking and pressing a key, so there will be 3 different combination of clicking and pressing. For example-
window.addEventListener("keydown", function(e){
if(e.keyCode === 16) {console.log('Yap! Shift works...');}
if(e.keyCode === 17) {console.log('Yap! Ctrl works...');
document.addEventListener('click',function (event) {
console.log(event.target.className);
}, false);
}
},false);
Now, when I press click shift key, I get related output, when I click Ctrl key and then click, I get the class name of the object I click on.
But the problem is, the output keeps coming as much I hold the key!! I want to execute the part of my code for once, and exactly when the key is pressed and a clicked is occurred.
How can I do that?
In general, how can I execute 3 part of code for three different tasks by clicking and pressing efficiently?
Adding an event handler while handing an event, is often the wrong way to solve a problem. Imagine how you will accumulate adding handlers... in your case there will eventually be many bindings to the same click handler.
It is better to bind the handlers you need immediately, and then work with keeping state on what exactly needs to happen while handling the event.
In these key handlers (keydown, keyup), keep track of whether the Shift/Control keys are depressed or not.
Also, use e.key as e.keyCode is deprecated.
Here is how that could work:
let keys = {
"Shift": false,
"Control": false
};
function keyToggle(e) {
if (!(e.key in keys)) return; // not ctrl or shift
let isKeyDown = e.type === "keydown";
if (isKeyDown === keys[e.key]) return; // key position did not change
keys[e.key] = isKeyDown;
console.log(e.key + (isKeyDown ? " pressed" : " released"));
}
document.addEventListener("keydown", keyToggle, false);
document.addEventListener("keyup", keyToggle, false);
document.addEventListener('click', function (e) {
if (keys["Control"]) console.log(event.target.className);
}, false);
<main class="main">Main</main>
<aside class="aside">Aside</aside>
As you addEventListener you can also removeEventListener.
For that you need a reference to your event handler, so you cannot use anonymous functions, but named functions or functions stored in a variable.
Edit
Here is an example of using CTRL+click:
// CTRL + CLICK implementation
let hasCtrl = false;
// Store the handler in a constant or variable
const handleClick = function(event) {
console.log(event.target.className);
}
// Use named function
function handleKeyDown(e) {
if (e.keyCode === 16) {
console.log('Yap! Shift works...');
}
}
const setCtrlInactive = (e) => {
if (!hasCtrl && e.keyCode === 17) {
console.log('Nope! Ctrl does not work...');
document.removeEventListener('click', handleClick);
hasCtrl = true;
}
}
const setCtrlActive = (e) => {
if (hasCtrl && e.keyCode === 17) {
console.log('Yap! Ctrl works...');
document.addEventListener('click', handleClick);
hasCtrl = false;
}
}
document.addEventListener("keyup", setCtrlInactive);
document.addEventListener("keydown", setCtrlActive);
document.addEventListener("keydown", handleKeyDown);
<main class="main">Main</main>
<aside class="aside">Aside</aside>
Well you can easily create an variable to lock it:
var locked = false;
window.addEventListener("keydown", function(e){
if(e.keyCode === 16 && !locked) {console.log('Yap! Shift works...'); locked =
true;}
if(e.keyCode === 17 && !locked ) {console.log('Yap! Ctrl works...');
locked = true;
}
},false);
document.addEventListener('click',function (event) {
if(locked){
// do something
console.log(event.target.className);
}
}, false);
window.addEventListener("keyup", function(){
locked = false;
}
That's because you called addEventListener('click') in the keydown event handler.
let ctrl = false;
window.addEventListener("keydown", function(e) {
if (e.keyCode === 16) {
console.log('Yap! Shift works...');
}
if (e.keyCode === 17 && ctrl === false) {
console.log('Yap! Ctrl works...');
ctrl = true;
}
});
window.addEventListener("keyup", function(e) {
if (e.keyCode === 17) {
ctrl = false;
}
});
document.addEventListener('click', function(event) {
if (ctrl) {
console.log(event.target.className);
}
}, false);
Instead, you should use keyup event and flag variable.

Call function with mouse click

I have a text area. Each time the enter key is entered the cursor travels to the next line of the text area and a function is called. This function posts/updates the entry in a database. I want it so that if I edit a line and then click on the mouse to resume typing at another line the function is again called on the mouse click
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
Is it possible to change my line to something like this and the method gets called on pressing the enter key or pressing the mouse(anywhere in the text area)?
if (e.keyCode == 13 || mouse.click) {
I know the above isn't correct but want to illustrate what I'm after
You could take use of jQuery's .on method like so:
$("#textarea").on('click keydown', (e) => {
if(e.keyCode && e.keyCode == 13 || e.type == "click" ){
// Do stuff
}
});
It takes a first parameter as string with different events, which mean you can listen to multiple events at once. The second is a callback function, where you can track the event that is triggered. Nb: Events are different between click and keydown. You can have a closer look by putting console.log(e); in your callback
You'll need to attach another event listener. The keydown event will not trigger when a mouse is clicked. You will need to add a $(...).click(function ...) as well. For example...
function myFunction (e) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
stream();
}
$("#textarea").keydown(function() {
if (e.keyCode == 13) {
myFunction()
e.preventDefault();
}
});
$('#textarea').click(myFunction)
Instead of putting a condition you can create 2 events and a common function to handle it.
Foe Example:
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
logic1()
$("#textarea").click(function() { logic1();});
function logic1(){
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
}
I don't know about jQuery but with vanilla JS you can do something like this:
const textarea = document.querySelector('textarea');
const foo = event => {
const output = document.querySelector('output');
output.textContent = event.type;
}
textarea.addEventListener('click', foo, false);
textarea.addEventListener('keypress', foo, false);
<textarea></textarea>
<output></output>

How can I create a behaviour where a key thinks it has been pressed whenever the mouse is pressed?

I have a babylonjs 3D scene where certain keys, when pressed, cause the camera to navigate forwards/backwards, etc. For example pressing T moves the viewer forward.
I am trying to generate an effect where the T key thinks it has been pressed whenever a mousedown occurs anywhere in the window. In short I need mousedown to move the camera forward.
document.addEventListener("mousedown", function(e) {
var code = 116;//T
$('document').trigger(
jQuery.Event('keypress', {
keyCode: code,
which: code
})
);
$("#show").append("mousedown creates: " + code + "<BR>");
});
document.addEventListener("keypress", function(e) {
var key = e.which;
//If it's the T key
if (key == 116) {
$("#show").append("T key has been pressed<BR>");
}
});
// I would like the mousedown event to fire the keypress event
// as if the T key has been pressed
The fiddle is here
This gets somewhat closer as the keypress event seems to occur. However the keycode doesn't come through. The output says "key: undefined."
function fire(type, options) {
var event = new CustomEvent(type);
for (var p in options) {
event[p] = options[p];
}
this.dispatchEvent(event);
}
window.addEventListener("mousedown", function(e) {
fire("keypress", {
keyCode: 116,
bubbles: true
})
});
window.addEventListener("keypress", function(e) {
var key = e.which;
$("#show").append("key: " + key + "<BR>");
if (key == 116) {
$("#show").append("T key was pressed<BR>");
}
});
The fiddle is here

How to prevent a "keypress" event firing a "click" event when focus is on a button - javascript/html dom

I have a button that fires a "stopstart" function (animation). I also want to have a mouseless method to do this so I've bound the same function to the space bar. This works.
However if focus is on the button, and I press space - both events fire, can't work out how to stop this (the keypress event fires first - in chrome..)
Eventlistener code:
document.getElementById("stopstart").addEventListener("click",
function (event) {
stopstart();
}); //add event listener to "stopstart" button
document.addEventListener("keypress",
function (event) {
if (event.keyCode === 32) { //space key
stopstart();
}
}); //add spacekey event listener to document
I don't want to remove focus from the button, as I'd like to retain that functionality - the two events appear to be separately generated - so I haven't found how to detect that the click event was in fact generated by the space bar.
Is this solvable using without having to add temporary flags to catch it etc
The click location for key events is zero, zero so you can look for that.
document.getElementById("stopstart").addEventListener("click",
function (event) {
var x = event.x || event.clientX;
var y = event.y || event.clientY;
if (!x && !y) {
alert("key press");
return false;
}
stopstart();
});
http://jsfiddle.net/mScEC/
function (event) {
if (event.pointerType !== "mouse") return;
stopstart();
}); //add event listener to "stopstart" button
document.addEventListener("keypress",
function (event) {
if (event.keyCode === 32) { //space key
stopstart();
}
}); //add spacekey event listener to document```
You can simply use event.preventDefault() inside keypress event Listener to prevent the Button Click event from getting triggered on keypress
e.g
document.addEventListener('keydown', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
try {
// if expression is not evaluated then catch block will be executed
screen.value = eval(screen.value);
}
catch (error) {
console.log(error.message);
screen.value = 'Invalid Operation';
}
}
})

How can I check that a key has been pressed?

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

Categories