use an event for each case (javascript switch) - javascript

Is it possible to specify e.preventDefault() once that will be work as same as the below code.
I mean I don't want to write e.preventDefault() each time if possible...
document.addEventListener("keydown", function(e) {
if (e.ctrlKey) { // Ctrl+
switch (e.keyCode) {
case 79: // O
e.preventDefault();
openDoc();
break;
case 83: // S
e.preventDefault();
saveDoc();
break;
case 66: // B
e.preventDefault();
showHideStatusBar(showStatusBar ? false : true);
break;
case 191: // /
e.preventDefault();
Help();
break;
}
}
});

You could try something like:
if (e.ctrlKey) { // Ctrl+
if (/^(79|83|66|191)$/.test(e.keyCode){
e.preventDefault();
}
switch (e.keyCode) { /*... */ }
}

Just place e.preventDefault() before the switch

Related

How to disable the event listener I called?

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

Binding arrow keys in jQuery except in input and textarea

I found this excellent question about binding the arrow keys with jQuery: Binding arrow keys in JS/jQuery with a great solution from Sygmoral:
$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
EXCEPT: This prevents the arrow keys from working the way they would usually work when the focus is in a text input field.
How would I modify this solution to allow the arrow keys to function normally when the current focus is in an input, text area, or another content editable area?
Put this in a condition:
$(document).keydown(function(e) {
if(!$(e.target).is(':input, [contenteditable]')){
switch(e.which){
// the cases as is
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
});
You can use event.target to get the target element of event, so you can check
var $target = $(e.target);
if($target.is("input") || $target.is("textarea")) {
//
}
Your editable element may have some common class
$('.input').keypress(function(event) {
var charCode = (evt.which) ? evt.which : event.keyCode
switch(charCode) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault();
});

How to detect whether switch() matches one of its cases?

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;

Keypress not firing In Firefox

I am using a JavaScript keypress switch to fire events, and it works fine in webkit browsers, but it does not work in Firefox. Can anyone help? The code I am using is:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
event.preventDefault();
alert("Arrow Key");
}
break;
case 37:
event.preventDefault();
alert("Arrow Key");
}
});
The functions I am trying to fire are more complex than just an alert, but i thought i would keep it simple for the explanation.
IIRC Firefox use charCode and not keyCode.
Can you try that :
$(document).keydown(function(e) {
kCode = (e.keyCode)? e.keyCode: e.charCode;
switch(kCode) {
case 39:
event.preventDefault();
alert("Arrow Key");
}
break;
case 37:
event.preventDefault();
alert("Arrow Key");
}
});
You have an syntax-error(a wrong bracket } before break;), and an undefined object(event) inside your function.
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
The wrong object(event) does'nt occur in MSIE, as there is always a global object called "event"

Prevent keypress event trigger when input is in focus

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.

Categories