keydown event for form or div in html - javascript

I am displaying a form inside a div tag as a dialog to enter details.
In this form, I want to handle the ESC key using jQuery.
If any input tags have focus, keydown event will trigger. If the focus is on the form but not on any input tags then it will not trigger keydown event.
Here is my code:
$("#NewTicket").keydown(function(e) {
var unicode = e.keyCode ? e.keyCode : e.charCode
if (unicode == 27)
{
if (confirm("Are you sure you want to cancel?"))
return true
else
return false
}
});

Just add an id,class to the form
<form id="form">
....
and now do this :
$("#NewTicket,#form").keydown(function(e)
{
var unicode=e.keyCode? e.keyCode : e.charCode
if(unicode == 27)
{
if (confirm("Are you sure you want to cancel?"))
return true
else
return false
}
)};
This should work

You can't focus on forms. If you wan't to handle keydown on elements that don't get focus (such as divs or forms) you have to bind it to the document.
Turns out that jQuery automatically adds :focus selector which enables you to find the focused element by using $(':focus')

I believe that if you put your form in an element made focusable using tabIndex, like , or this focusable div is the container element inside the form, then you can bind the keyDown to this div instead. It works cross browser as far as I've tested but I've not seen this solution discussed much, so curious as to anyone's comments about this.

I know this is an old question but someone still might be looking for an answer.
Usually, I do capture key down at global level then forward it to a function and handle it there. For your needs, you can get nodeName. (Tested in FF, Chrome)
$(document).keydown((e)=>{//Capture Key
if(["INPUT","TEXTAREA"].indexOf(e.target.nodeName)!==-1){//If input in focus
console.log("INPUT FOCUSED",e.code,e.keyCode);
if(e.keyCode==27 || e.code=="Escape"){//Capture Escape key
console.log('ESC');
}
}
});

Related

how to prevent the default shortcut triggering from browser

Well, Im trying to make a custom shortcut for a web application. But I have a little problem ( I tried to find a solution but I only found the preventDefault and shortcut.add , I didnt understand well the second one)
I want to know how can I use the custom shortcut of my code without calling the browser shortcut. And if I use shift key the default shotcut wont disable the uppercase writing.
thx a lot for the help, greetings from chile.
var menu_abierto=false;
$(document).on('keypress',function(e){
if(e.which==69 && e.ctrlKey && menu_abierto==false){
$('.btn-1,.btn-2 ,.btn-3').prop('disabled',true);
$('#lista-emergencias').show();
MenuLateralIzq();
listarEmergencias();
menu_abierto=true;
} else if(e.which==69 && e.ctrltKey){
$('.btn-1 ,.btn-2, .btn-3').prop("disabled",false);
$('#lista-emergencias ul li').remove();
$('#lista-emergencias ul hr').remove();
$('#lista-emergencias').hide();
OcultarMenuIzq();
menu_abierto=false;
}
});
You have to add e.preventDefault() to prevent the default browser action and then come your custom action :
if( e.target.tagName.toUpperCase() != 'INPUT' ){
if(e.which==69 && e.ctrlKey && menu_abierto==false){
e.preventDefault();
$('.btn-1,.btn-2 ,.btn-3').prop('disabled',true);
$('#lista-emergencias').show();
MenuLateralIzq();
listarEmergencias();
menu_abierto=true;
} else if(e.which==69 && e.ctrltKey){
e.preventDefault();
$('.btn-1 ,.btn-2, .btn-3').prop("disabled",false);
$('#lista-emergencias ul li').remove();
$('#lista-emergencias ul hr').remove();
$('#lista-emergencias').hide();
OcultarMenuIzq();
menu_abierto=false;
}
}
Add if( e.target.tagName.toUpperCase() != 'INPUT' ){ if you want to disable this for inputs.
Explanation :
e.target mean the current selected element, tagName get the type of this element incase of input field that will return INPUT, toUpperCase() just to make sure that the INPUT string returned is on mode UpperCase, != 'INPUT' mean if not input in other words if the element selected is not an input field then you can replace the browser shortcuts by the customs ones.
Check SO question/answers javascript capture browser shortcuts (ctrl+t/n/w).
Hope this helps.
You need to set 2 things:
e.stopPropagation()
Prevents further propagation of the current event.
e.preventDefault()
Cancels the event if it is cancelable, without stopping further propagation of the event.

Prevent space button from triggering any other button click in jQuery

I have an application where I am using the space bar to toggle a function anywhere in the window. However, if any other button or checkbox has focus, then that gets clicked as well.
I tried preventDefault() but that didn't work out as expected. How can I ensure that no other element on the screen gets clicked when I press the spacebar?
HTML
<button class="buttons" id="playBtn">PLAY</button>
JS (Updated according to Using prevent default to take over spacebar
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '32') {
if (event.stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
playBtn_DOM.click();
} else if (keycode == '97') {
event.preventDefault();
prevBtn_DOM.click();
} else if (keycode == '100') {
event.preventDefault();
nextBtn_DOM.click();
}
});
And with respect to answer Using prevent default to take over spacebar, that solution didn't work. I have updated the JS code to show that I tried including the solution given there.
I also had this problem and after a bit of fiddling found that it's keyup that triggers button clicks. I've made a fiddle that demonstrates this: https://jsfiddle.net/Beppe/o6gfertu/1/. It works in Firefox and Chrome, although in the latter the button changes appearance to look pressed.
Simply use
$(element).blur();
to unfocus any element (like button) when it is focused (like click event for button).
For those who are expecting SPACE in some text input within clickable DIV. Try this:
HTML:
<div id="someClickableDiv" onclick="doSomething()">
<textarea onkeyup="event.preventDefault()"></textarea>
</div>
Or Angular 6 version:
<div id="someClickableDiv" (click)"doSomething()">
<textarea (keyup)="$event.preventDefault()"></textarea>
</div>
This will remove focus from all buttons as soon as they are focused (e.g. by a click). This will prevent spacebar from ever activating buttons.
document.querySelectorAll("button").forEach( function(item) {
item.addEventListener('focus', function() {
this.blur();
})
})
I found a relatively hacky solution to this. Better answers are most welcome!
$(document).mousemove(function(event){
if (document.activeElement != document.body) document.activeElement.blur();
});
Basically, it checks if mouse is anywhere in document's body. If yes, then it blurs any other element that has focus.

jQuery plugin not firing correction keydown or idle events

I am programming a jQuery plugin which tracks specific events. I have provided 2 JSFiddle examples for the sanitised code to assist at the end of the question.
I am struggling to fathom why 2 particular events are not firing. The first function tracks when the user triggers the backspace or delete keys within an input or textarea field. The code for this:
// Keydown events
$this.keydown(function (e) {
var keyCode = e.keyCode || e.which;
// Tab key
if (e.keyCode === 9) {
alert('tab key');
} else if (e.keyCode === 8 || e.keyCode === 46) { // Backspace and Delete keys
if ($this.val() !== '') {
alert('Backspace or delete key');
}
}
});
I only wish to track the error-correction keys when a field is not empty. The tab key in the above example works as expected within the conditional statement. The backspace and delete keys do not work when inside the plugin and targeting the element in focus.
The second event not firing is tracking whether a user becomes idle. It is making use of jQuery idle timer plugin to manipulate the element in focus.
// Idle event
$this.focus(function() {
$this.idleTimer(3000).bind('idle.idleTimer', function() {
alert('Gone idle');
});
}).focusout(function() {
$this.idleTimer('destroy');
});
With both of these events I have refactored the code. They were outside of the plugin and targeted $('input, select, textarea') and worked as expected. I have brought them inside the plugin, and set them to $(this) to manipulate elements currently in focus. For most of the functions, this has worked without fault, but these 2 are proving problematic.
The first JSFiddle is with the 2 functions inside the plugin. tab works, whereas the correction keys do not. Strangely, in this example the idle function is firing (it does not in my dev environment). As this is working in the JSFiddle, I accept this may be difficult to resolve. Perhaps suggestions on handling an external plugin within my own to remedy this?
Fiddle 1
The second JSFiddle has taken the backspace and delete key functionality outside of the plugin and targets $('input, select, textarea') and now works.
Fiddle 2
For Fiddle1:
if ($this.val() !== '') {
alert('Backspace or delete key');
}
Look at what $this actually is.

disable tabbing on document but enable input tabbing?

I have added the following code to my site to prevent tabbing, this applies to the whole document. Problem is that this obviously disables all tabbing throughout the site, how can I add a rule in to allow inputs to be tabbed? I tried adding .not('input') but this doesnt seem to work.
$(document).keydown(function(objEvent) {
if (objEvent.keyCode == 9) {
objEvent.preventDefault();
}
});
Thanks
You can check the value of document.activeElement.tagName.
If nothing is selected, document.activeElement will be the body tag in FireFox, Chrome, and the html tag in IE 7/8/9.
$(document).keydown(function(objEvent) {
if (objEvent.keyCode == 9) {
if (document.activeElement.tagName != 'INPUT')
objEvent.preventDefault();
}
});
The keyup event properly also sends a target with it.
objEvent.target should return the current target the user is at.
So checking up on if the target is an input field then ignore the preventDefault...
Edit: Not sure if this is gonna work. "wsanville" method looks more legit.

How do write a JavaScript function that allows for non-editable textbox?

I need to have an input textbox in which I can click and the cursor starts blinking but the user cannot change any text inside it.
I tried using "readonly" or "disabled" attributes, but they do not allow the cursor to be inside the textbox. So, I was thinking of a solution to implement in JavaScript on a normal textbox. Is there a plugin that already do this? How do I implement this?
EDIT: Thanks for all the answers, but I wanted to make the textarea/input type text as uneditable but selectable at the same time. Pressing Ctrl + A inside the textbox doesn't work. Is it possible to get the changed value and the old value and compare them and then return false if the values are different, but in all other cases return true so that the Ctrl + A, Shift + end, etc. combinations work?
Something like this:
<textarea onkeydown="javascript:return false;"></textarea>
would do the trick. (jsfiddle)
You can also do that at runtime if you want to:
<textarea class="readonly"></textarea>
with
$(".readonly").keydown(function() false);
The onkeydown callback captures keystroke events and cancels them using return false;.
Depending on what you are trying to do, you may want to prevent other kind of events, since it is still possible to change the contents with the mouse, for instance.
Your callback function can accept or cancel events depending of the kind of keystroke. For example, to enable only ctrl-a and ctrl-c (with jQuery):
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
$(function(){
$("inputSelector").keydown(function(){ return false; });
});
You cannot rely on disabling a <textarea> as a user input, as it's trivial to remove any sort of HTML or javascript disabling with firebug, or other tools. Remember that forms aren't limited to the fields you give them, anyone can submit any data to a page.
Disabled inputs are not submitted with a form anyway, bearing that in mind my advice would be to not use a textarea and just print it out.

Categories