I have a code like this:
$("textarea").on('keydown', function(e){
if(e.ctrlKey){ // Ctrl is pressed
switch (e.which) {
case 66: // "B" button on the keyboard
alert("it is bold");
break;
case 73: // "I" button on the keyboard
alert("it is italic");
break;
}
e.preventDefault();
return false;
}
});
The above code handles Ctrl + B and Ctrl + I on keydown of textarea. Also there is two lines of code which stop every things:
e.preventDefault();
return false;
This ^ codes stops the action of any button. For example Ctrl + S is deactivate now ..! What I need is to define if that switch() function matches a case, then run those two lines, else don't run those two lines. How can I do that?
Try like this if key press other then Ctrl+B or Ctrl+I then it won't do anything.
$("textarea").on('keydown', function(e){
if(e.ctrlKey){ // Ctrl is pressed
var codes= [66,73];
var a = codes.indexOf(e.which);
if(a > 0){
return false;
}else{
// your stuff
}
}
});
Use the default case!
switch (e.which) {
case 66: // "B" button on the keyboard
alert("it is bold");
break;
case 73: // "I" button on the keyboard
alert("it is italic");
break;
default: // everything else
return; // without preventing the default action
}
e.preventDefault();
return false;
Related
I assign an event listener inside the first function whenever I press the 1 in my keyboard which is 49 in keyCode it will trigger the first function which will console the A and S whenever you try to press it. then if I press the 2 in my keyboard which is 50 in keyCode it will then trigger the second function which will console the D and F whenever you press it. My problem is after I called the first function then call the second function, how can I disable the first function that will prevent the press of A and S ? In short, how to disable the event listener of function I called whenever I will call the new function ?
<body>
</body>
<script>
document.body.addEventListener('keydown',function(e){
if(e.keyCode == 49){
document.body.addEventListener('keydown',function(e){
switch(e.keyCode){
case 65:
console.log('you pressed A')
break;
case 83:
console.log('you pressed s')
break
}
})
}else if(e.keyCode == 50){
document.body.addEventListener('keydown',function(e){
switch(e.keyCode){
case 68:
console.log('you pressed d')
break;
case 70:
console.log('you pressed f')
break
}
})
}
});
</script>
To remove an event listener, the function must have a name to reference, so that you can reference which event listener to remove. For example:
function myFunction() {
// code here
}
document.body.addEventListener("keydown", myFunction);
and to remove it:
document.body.removeEventListener("keydown", myFunction);
Without assigning functions to names, JavaScript doesn't know which event listener to remove, because you can have multiple functions binded to one element.
So to change up your code, it should be:
document.body.addEventListener("keydown",function(e) {
if (e.keyCode == 49) {
document.body.addEventListener("keydown", verticalMoves);
} else if (e.keyCode == 50) {
document.body.addEventListener("keydown", horizontalMoves);
}
}
function verticalMoves(e) {
switch(e.keyCode) {
case 65: console.log("you pressed A"); break;
case 83: console.log("you pressed S"); break;
}
document.body.removeEventListener("keydown", verticalMoves);
}
function horizontalMoves(e) {
switch(e.keyCode) {
case 68: console.log("you pressed D"); break;
case 70: console.log("you pressed F"); break;
}
document.body.removeEventListener("keydown", horizontalMoves);
}
This is my additional code for reddit. It helps me browse it much quicker. The idea is based on 4chan's keyboard shortcuts. 'N' key for the next page and 'B' for the previous.
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e){
switch(e.keyCode){
case 66:
window.location = document.querySelector('a[rel="nofollow prev"]').href;
break;
case 78:
window.location = document.querySelector('a[rel="nofollow next"]').href;
break;
default:
}
}
My problem is, the event also occurs when I type into a text field with the words that has 'n' or 'b' in it. How do I prevent it from happening when I focus to a text field?
As noted out by zerkms: i am not sure if you also want to detect text area's you should enhance the code further if you need support for such case...
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e){
var elem = e.target;
var type = elem.getAttribute("type");
if(type!='text'){
switch(e.keyCode){
case 66:
//window.location = document.querySelector('a[rel="nofollow prev"]').href;
alert("case 66");
break;
case 78:
//window.location = document.querySelector('a[rel="nofollow next"]').href;
alert("case 78");
break;
default:
}
}
}
I'm new here and also new with web coding. So i am trying to make a function to move my game character when a button is pressed. When button is pressed down a boolean value changes to "true" and the character moves. I was trying to do it somehow like this. Can someone light me up what is the best way to make this work? I need also to do this for all the rest buttons (a,s,d,arrows).
var wButton = false;
function newfunction()
document.querySelector('#keyButtonW').addEventListener('mousedown', function(event) {
keyButtonPressed("wButton", true);
});
document.querySelector('#keyButtonW').addEventListener('mouseup', function(event) {
keyButtonPressed("wButton", false);
});
document.querySelector('#keyButtonW').addEventListener('mouseleave', function(event) {
keyButtonPressed("wButton", false);
});
Assuming translate is a method to move your char, maybe you should make a big maskArray :
var keyboard = [];
function keyDown(e)
{
var key = event.keyCode || event.which;
keyboard[key] = true;
}
function keyUp(e)
{
var key = event.keyCode || event.which;
delete keyboard[key];
}
function keyAction() {
for (i in keyboard)
{
if (keyboard[i] == true)
{
switch(eval(i))
{
case 90: //Z
character.translateY(-1);
break;
case 83: //S
character.translateY(1);
break;
case 81: //Q
character.translateX(-1);
break;
case 68: //D
character.translateX(1);
break;
}
}
}
return false;
}
document.addEventListener("keydown", keyDown, false);
document.addEventListener("keyup", keyUp, false);
Simply put keyAction() inside your main loop / rendering loop.
The value of this is to not make lags happen when you hit a button, and help with multiple pressing management =)
EDIT
To get the key numbers, simply put a console.log(key) at the end of keyDown().
I am using reveal.js by Hakim El Hattab to make presentation slides. I have added textarea to a slide. Within the textarea I want to prevent javascript functions from being called when certain keys are pressed, and restore the default behavior of typing. For example, as you can see from the lines of code below from reveal.js, when p is pressed, a function navigatePrev() is called. I want to prevent this function from being called and simply want p to be typed in the textarea when p is pressed. How can I do this using jquery? I tried adding the following script but that does not help.
<script>
$(document).keydown(function (e) {
if ($(e.target).is('textarea')) {
e.stopPropagation();
}
})
</script>
The functions defined in the reveal.js are still called. Using return false in place of e.stopPropagation() does not help either. I am also including the above jQuery lines at the very end on my page (after reveal.js is called).
Thank you.
Relevant lines from reveal.js
function onDocumentKeyDown(event) {
// FFT: Use document.querySelector( ':focus' ) === null
// instead of checking contentEditable?
// Disregard the event if the target is editable or a
// modifier is present
if (event.target.contentEditable != 'inherit' || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
var triggered = false;
switch (event.keyCode) {
// p, page up
case 80: case 33: navigatePrev(); triggered = true; break;
// n, page down
case 78: case 34: navigateNext(); triggered = true; break;
// h, left
case 72: case 37: navigateLeft(); triggered = true; break;
// l, right
case 76: case 39: navigateRight(); triggered = true; break;
// k, up
case 75: case 38: navigateUp(); triggered = true; break;
// j, down
case 74: case 40: navigateDown(); triggered = true; break;
// home
case 36: navigateTo(0); triggered = true; break;
// end
case 35: navigateTo(Number.MAX_VALUE); triggered = true; break;
// space
case 32: overviewIsActive() ? deactivateOverview() : navigateNext(); triggered = true; break;
// return
case 13: if (overviewIsActive()) { deactivateOverview(); triggered = true; } break;
}
}
The problem with your keydown event binding is that it binds to the document, which receives the event LAST (once it's too late to prevent the event from bubbling further up the DOM tree).
Instead, try binding the event directly to the textarea every time it is created:
// create text area & append to slide container
createTextAreaOnSlideContainer();
// bind an event handler to the element
$('textarea.slideTextArea').keydown( function(e) {
e.stopPropagation();
});
This will stop the event before it bubbles (propagates) up to the document that is listening for a key to be pressed
You can do this:
$(document).keydown(function(e){
if(!$('#textarea').is(':focus')){
yourfunction();
}
});
You just simply add an if statement inside and if the textarea is not focused then you call the function.
I am currently using a switch to trigger some code when a key is pressed. This isn't the exact code, but its basically what I am using (this is just for the sake of keeping it short and simple on here.)
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
How can I prevent the events from firing when an input box is in focus?
I think you mean that you want to do e.preventDefault() only if the target element was not an input tag. You can do this like this:
$(document).keydown(function(e) {
if (e.target.nodeName.toLowerCase() !== 'input') {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
}
});
e.target is the element where the event originated. Alternatively, you can use jQuery's event delegation API:
$(document).delegate(':not(input)', 'keydown', function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
Edit Updated my answer to do "not an input" rather than "is an input" checks.
You can use document.activeElement which returns the currently focused element.
Brief doc from the MDN:
Returns the currently focused element, that is, the element that will get keystroke events if the user types any. This attribute is read only.
That is, in order to prevent keystroke events from firing when input is in focus, you can just ignore keystroke events handling when the focused element is an input
if (!$(document.activeElement).is("input"){ /* handle keystroke events here */ }
There may be a more elegant way but I would do something like this:
var inputHasFocus = false;
$("#some_input_id").focusin(function () {
inputHasFocus = true;
}).focusout(function () {
inputHasFocus = false;
});
and then use that in your case statement.