I noticed that if you focus on an element that mouse clic can be triggered, the Enter keys acts like as you left click the mouse. I want to avoid this running since it comes into conflict in other pieces of my code.
In the following example if I focus on this imageButton and I clic once, the next clicks can be "done" with the Enter key, so I don't want this because this button fires a slideToggle() and shows a hidden div, so IMO it's pointless toggle this div with the keyboard.
Is there any way to make it global way?
Thank you.
Try this:
$(".myElements").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
It will stop the enter key behaviour only, allowing the other key functions to work as usual.
Listen for "keypress" and .preventDefault()
ex. with <myelm class="nokey"/>
function noKeyPressing(){
var elms = document.getElementsByClassName('nokey'),
stop = function stop(e){ return e.preventDefault(), false; },
i = elms.length;
while(--i >= 0){
elms[i].addEventListener('keypress', stop, true);
}
}
noKeyPressing()
If you just want to prevent Enter then the keyCode to look for is 13.
try
.unbind('keydown');
to disable all key events on your element
You can return false to prevent the default action.
<input type="submit" onkeypress="return false;" value="Submit" />
An other possible way i think:
$('.elems').on('click',function(){$(this).blur()});
try this code
$('body *').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
}
});
the above code will prevent pressing enter for every element in page
,You can change the selector $('body *') to something else depending to your case
Related
I am trying to change the behaviour of selects in an html form.
I would like that when a user navigates the form using the keyboard, if they are selecting an element and presses tab, the element is selected and the focus switches to the next form input. Normally, you need to press enter to select the element and then you can use tab to switch to the next one. If enter isn't pressed, no option is selected.
To do this, I want to capture the TAB keypress and trigger an ENTER keypress followed by a TAB.
This is what I have for now:
$('form[class="ui form"]').on('keydown', 'div[class="ui fluid selection dropdown active visible"]', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var y = jQuery.Event('keydown', {which: 13});
$(this).trigger(y);
var x = jQuery.Event('keydown', {which: 9});
$(this).trigger(x);
}
});
Here is a demo: JSFiddle
The code 'works' up to e.preventDefault(), the tab keypress doesn't switch the focus to the next input. However, the enter and tab actions aren't triggered, so nothing happens. What should I do ?
Thank you in advance !
UPDATE 10/10: Found the problem! Triggering event x (tab keypress) makes the code enter an infinite loop. Therefore the whole approach is wrong. I'll soon post an answer.
When I try it passing whichas the event object, it does work jsfiddle.net/mendesjuan/sL7tnfm6/5
$('form[class="ui form"]').on('keydown', 'div[class="ui fluid selection dropdown active visible"]', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var y = jQuery.Event('keydown', {which: 13});
$(this).trigger(y);
}
});
The draft code in the question triggers an infinite loop. The key point in the problem is capturing the selected (active) element when the user presses TAB and switches the focus to the next element.
So, it is better to use a function called onblur:
$('form[class="ui form"]').on('blur', '.dropdown', function () {
var y = jQuery.Event('keydown', {which: 13});
$(this).trigger(y);
});
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.
JavaScript (JQuery)
$('input').keyup(function(e)
{
var code = e.keyCode ? e.keyCode : e.which;
switch(code)
{
case 38:
break;
case 40:
break;
case 13:
break;
default:
return;
}
});
HTML
<form method="post" action="/">
<input type="text" name="text" />
<button type="submit">Submit</button>
</form>
I have 2 problems:
1) The caret shouldn't move when I hit the up arrow key.
For example, in Chrome when I hit the up-key it moves the caret to the left. But I only have this problem in Chrome. It works fine in FF.
2) When I hit the enter key, I don't want the form to be submitted.
BTW, I want to get this to work with keyup and not keypress.
I'd appreciate any ideas. Thanks.
I don't think you can preventDefault() (which is what you'd need to use to stop the browser from performing the default action for a key) on the keyup event - it is fired after the default event has already occurred. See this page for more.
If you can, consider using the keydown instead.
As for stopping the form from submitting, you could bind to the submit event and return false; when the submit was not triggered by the submit button (see jQuery: how to get which button was clicked upon form submission? for how to determine this).
On the other hand, you could also bind to keypress for the form and when Enter is pressed, cancel submission the same way (untested code):
$('form').keypress(function(e){
if(e.which === 13){
return false;
}
});
Instead of break you could try return false or make it call a function and use http://api.jquery.com/event.preventDefault/
For example: case 40: function(e) {e.preventDefault;}
Also, $('form').submit(function() {return false}); would stop submissions altogether, but I'm not sure that's what you're after?
In order to prevent the form being submitted when the user presses enter you need to bind the submit function of your form and return false if the event trigger was the enter button being pressed.
for the Up/Down button press, use e.preventDefault();
The most reliable method is a combination of e.preventDefault(), e.stopPropagation() and return false;
Here's what it might look like:
var override_keys = [13, 38, 40];
$('input').keyup(function(e){
var code = e.keyCode ? e.keyCode : e.which;
if ($.inArray(code, override_keys)) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
Also, to prevent the form from being submitted with the enter key you should check the form's submit event:
$('#form').submit(function(e){
var code = e.keyCode ? e.keyCode : e.which;
if ($.inArray(code, override_keys)) {
return false;
}
});
It seems like that you actually CAN stop the default for 'ENTER' while using keyup(); ... jQuery api writes about it themselves here: http://api.jquery.com/keyup/
Here's how you have to do:
$('textarea').keyup(function(e) {
// your code here
}).keydown(function(e){
// your e.which for ENTER.
});
What's the simplest way to have a function called whenever the user hits enter after typing in a textbox?
You'll need to listen for the keypress event. It's probably easiest to do this with delegate:
$(document.body).delegate('input:text', 'keypress', function(e) {
if (e.which === 13) { // if is enter
e.preventDefault(); // don't submit form
// do what you want here
}
});
<textarea id="text"></textarea>
$('#text').keydown(function(e){
if (e.keyCode == 13) {
alert('Enter was pressed.');
}
});
http://jsfiddle.net/dNfC2/
HTML code
<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>
jquery code
$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});
Running example here : http://jsfiddle.net/Xamkp/5/
try this:
jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });
you will need a plugin:
jquery.hotkeys
Well it's rather simple to do in the form you asked:
$('#idOfTextBox').keyup(function(event){
// enter key pressed
if(event.keyCode=='13')yourFunction();
});
Take note this will still append the enter key to the box. You might wanna try keydown or keypressed if you don't want that.
Be sure to check keyUp() for more detail.
Put the <input> in a form, and write a handler for the form's submit event.
This way you're not explicitly looking for any particular key; you're just waiting for the form to be submitted normally. And in every mainstream browser, pressing enter while filling out a form will submit the form.
Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form).
Users don't like the fact that the Enter key submits the page. So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.
I have tried many javascript snippets found on the net but none have worked so far. The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.
e.returnValue = false;
e.cancel = true;
Page still submits with the above in the keydown event handler. Same effect with return false in the keydown event handler. The handler is firing, tested by putting a breakpoint in it with firebug.
This needs to work with both IE and Firefox.
Don't say "don't do this".
1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.
2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.
This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:
Here's a simple example:
$("input").bind("keydown", function(event) {
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
$(this).next("input").focus();
}
});
Example: http://jsfiddle.net/andrewwhitaker/Txg65/
Update: If you have elements in between your inputs, using plain next() will not work. Instead, use nextAll():
$("input").bind("keydown", function(event) {
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
$(this).nextAll("input").eq(0).focus();
}
});
http://jsfiddle.net/andrewwhitaker/GRtQY/
$("input").bind("keydown", function(event) {
if (event.which === 13 && this.type !== 'submit') {
event.preventDefault();
$(this).next("input").focus();
}
});
Based on this post:
http://forum.jquery.com/topic/how-to-find-next-node-in-focus-order
I came up with this. I eventually chose not to use focasables though, and instead use input to get the effect I wanted. The .not is to prevent image buttons and submit buttons from being effected, so that they still have the default action of submit on enter whenever they have focus.
$(document).ready(function() {
var focusables = $(":input").not('[type="image"]').not('[type="submit"]');
focusables.keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
}
});
});