I'm having some buttons that can be clicked either by mouse or key presses. Then I have a function called by space-key.
The problem is that when one of the buttons has been clicked with mouse, it seems the button gets selected (focussed) and when the space-key (and enter-key) gets pressed afterwards, the browser calls the selected (focussed) button instead of the intended function for the space key.
I've found a solution long time ago so I know there is a solution but can't remember.
Edit: This is not inside a form.
If you don't need the spacebar for your form, you can do an event.preventDefaut() on keypress for the spacebar.
$(yourbuttonelements).keydown(function(e) {
var kc = e.keyCode;
if (kc === 32){
e.preventDefault();
}
});
If you wish to bypass the default event on a keypress, you need to first delegate a 'keypress' or related event and then check for event.which to find the corresponding key pressed and if it matches with what you want to prevent, you can either do return false; or do event.preventDefault();
Example :
$('button').on('keypress',function(e)
{
if(e.which == 32) // 32 -> represents the keycode of space bar
e.preventDefault();
});
preventDefault() didn't work though I found a solution.
As mentioned, the problem was the button got focussed when clicked, so I used blur() for the button.
document.getElementById(id).blur();
Related
I am trying to intercept "Hide keyboard button" specific for Ipad in Javascript. I searched everywhere but could not find correct keycode for that.
I pressed any keys and I get a keycode map (for characters, but also for enter, space and delete..).
This is an example of what I want to accomplish
$( "#mydiv" ).on( "keydown", function( event ) {
if (event.which == xx){
//do something
}
}
where xx is my keycode on 'hide keyboard button'. No method is called to the delegate when the button is pressed nor a KeyCode.
I took a look at detect iPad keyboard Hiding button, but I get a solution on a different level (with Xcode), but I need a solution with Javascript.
Hope someone could help.
I found a workaroud for iPad IOS7. I will test on IOS8 to make sure it works. So basically I create a listener on every FOCUSOUT event (for all my texts) and I call my function.
It fires when you have your keyboard open and when you close your "keyboard". It doesn't fire when you select another text field or button, because it targets on null. If you use in combination with keydown, you can save multiple value and call your submit function only when you release your keyboard.
It works for my specific project.
document.addEventListener('focusout', function(e) {
if (e.relatedTarget === null) {
alert("close keyboard without click on something else");
callYourFunction();
}
});
p.s
I'm pretty new here in SO, so I don't know if I can reply myself or I should edit my question or make a comment.
See code:
area.onkeydown = function(e){
e = e || window.event;
if(e.shiftKey && e.keyCode === 32){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// no alert here
return false;
}
};
Here, the code works, and on pressing Shift + Space, the space doesn't get inserted. However, as soon I insert an alert, it doesn't work, i.e. the space gets inserted and the alert box also doesn't show.
area.onkeydown = function(e){
e = e || window.event;
if(e.shiftKey && e.keyCode === 32){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
alert("typed"); // this alert doesn't show
return false; // and space also gets insrted
}
};
FIDDLE
What am I missing?
UPDATE:
Using onkeyup would show the alert, but a space gets inserted.
Using onkeypress would not insert the space, but the alert stays as long as the keys remain pressed.
So, I guess there is no way for me to get this working. And as Teemu puts it:
At your fiddle the snippet works with or without alert() without printing the space in IE11 (Win7). FF loses the preventDefault() behavior, though I can see the alert. In Chrome35 the alert only flashes on the screen and the space is printed. (If the flash is fast enough, your case?) IE uses an OS window to show an alert, other browsers have their own implementation, which seems to mess up the event handling.
UPDATE: I'm voting to close this question as off-topic because the problem can no longer be reproduced, the way it was described, in that fiddle in the latest Chrome version. Pressing Shift+Space now shows the alert box but does NOT insert any space.
i've change your keydown to keyup
See this
area.onkeyup = function(e){}
Try with onkeypress instead of onkeydown
Using Keyup instead of keydown reason is as below:
area.onkeyup = function(e){
Demo
Keydown:
The keydown event is sent to an element when the user first presses a
key on the keyboard. It can be attached to any element, but the event
is only sent to the element that has the focus. Focusable elements can
vary between browsers, but form elements can always get focus so are
reasonable candidates for this event type.
Keyup:
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus. Focusable elements can vary
between browsers, but form elements can always get focus so are
reasonable candidates for this event type.
In my asp.net solution, I have a text input box and a search button. There is a onkeyup jquery event on the text input field so it automatically clicks the search button when the user presses a key. You can also manually click the button.
But what I noticed is that if you are typing, and then you press ENTER key, it will trigger the on onkeyup event. How can I disable the function from occurring if the ENTER key was pressed, or maybe detect if it was the ENTER key and then have an if statement or something.
Another thing that is happening is, if there is something wrong with the text in the input box, I display an alert message box. Then if you press ENTER to close the box, it will somehow trigger the onkeyup event, which displays the alert box again...
Thanks.
add if (evt.keyCode != 13) in front of all actions in the function :)
You can use .which on the event to determine the KeyCode for the key that was pressed (ENTER = 13):
$('#input').keyup(function(event) {
if(event.which == 13)
{
//respond to enter keypress
}
});
Also you can use this site to easily find info about keyups/downs etc for different keys.
Hope this helps!
Hope this helps.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The onkeyup event is triggered after an alert when you close it with ENTER because the alert is close onkeydown, and so after it's closed and the document regains focus, when you release the key, the textbox's onkeyup event will be triggered.
As previously stated, you can add an if (event.keyCode != 13) to test if the ENTER key is not the key that was pressed.
A better solution would be to use a different event.
Instead of onkeyup, use oninput.
The oninput event is triggered when the user changes the textbox's value.
The event will fire only when the user writes something in the textbox or deletes something. It will not go off when the ENTER key is pressed, or when any other key that doesn't change the textbox's value (like arrow keys) is pressed.
The oninput event might be a better choice for the functionality you're searching for.
*if you're using the oninput event you don't need the if mentioned before.
A fiddle for demonstration of the oninput event: Here
For future reference I found this useful site:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Good luck!
My App will allow people to write in a canvas, so I have attached a event listener to the keypress key, this fires the following function:
var Keypress = function(event) {
if (event.keyCode == 8) {
chatRoom.removeLetter();
event.preventDefault();
}
if(event.keyCode == 13){
chatRoom.newLine();
}
chatRoom.addText(event.charCode,"White");
}
the issue is this, currently if someone hits backspace 1 character can get deleted then, backspace gets frozen and can not be used again until another key is pressed. However is what I am looking for is for backspace to be able to be hit many times, many characters get deleted and no one ends up going back a page.
In essense I am trying to find a way for the function to fire the removeLetter() event and just disable going back on the browser, However all examples I have seen ever freeze up the backspace (leading to this one letter can be deleted) or do not work (return false would just not work at all for me).
The problem is that you're writing the backspace 'character' to you chatroom. Thus, when you press backspace the second time, you're just deleting that backspace character, and then rewriting it.
Try returning after removing your letter:
if (event.keyCode == 8) {
chatRoom.removeLetter();
event.preventDefault();
return;
}
I have a JQuery scroller on a page where each item is a div with an id. each div has a link to the next div in the scroller (all on the same page)
$('a.panel').click(function () {
};
I have a click event to all links with the 'panel' class where I check which links was clicked and then do some ajax processing accordingly:
if($(this).attr('href')=="#item2")
{
//do some processsing
}
and once the processing is done I use the scrollTo JQuery method to scroll to the next div
I need to have it that the user can press the enter key instead of clicking on the link.
Now the problem is:
a. I have several links on the same page that all need to have this behaviour.
b. I need to differentiate which link triggered the click event and do some server-side processing.
Is this possible at all?
I appreciate the quick and helpful responses!!Thanks a million for the help!
Focus + enter will trigger the click event, but only if the anchor has an href attribute (at least in some browsers, like latest Firefox). Works:
$('<a />').attr('href', '#anythingWillDo').on('click', function () {
alert('Has href so can be triggered via keyboard.');
// suppress hash update if desired
return false;
}).text('Works').appendTo('body');
Doesn't work (browser probably thinks there's no action to take):
$('<a />').on('click', function () {
alert('No href so can\'t be triggered via keyboard.');
}).text('Doesn\'t work').appendTo('body');
You can trigger() the click event of whichever element you want when the enter key is pressed. Example:
$(document).keypress(function(e) {
if ((e.keyCode || e.which) == 13) {
// Enter key pressed
$('a').trigger('click');
}
});
$('a').click(function(e) {
e.preventDefault();
// Link clicked
});
Demo: http://jsfiddle.net/eHXwz/1/
You'll just have to figure out which specific element to trigger the click on, but that depends on how/what you are doing. I will say that I don't really recommend this, but I will give you the benefit of the doubt.
A better option, in my opinion, would be to focus() the link that should be clicked instead, and let the user optionally press enter, which will fire the click event anyways.
I would like to focus on the link, but am unfamiliar exactly how to do this, can you explain?
Just use $(element).focus(). But once again, you'll have to be more specific, and have a way to determine which element should receive focus, and when. Of course the user, may take an action that will cause the link to lose focus, like clicking somewhere else. I have no idea what your app does or acts like though, so just do what you think is best, but remember that users already expect a certain kind of behavior from their browsers and will likely not realize they need to press "enter" unless you tell them to.
If you do choose to use the "press enter" method instead of focusing the link, you'll likely want to bind() and unbind() the keypress function too, so it doesn't get called when you don't need it.
http://api.jquery.com/focus/
http://api.jquery.com/bind/
http://api.jquery.com/unbind/
Related:
Submitting a form on 'Enter' with jQuery?
jQuery Event Keypress: Which key was pressed?
Use e.target or this keyword to determine which link triggered the event.
$('a.panel').click(function (e) {
//e.target or this will give you the element which triggered this event.
};
$('a.panel').live('keyup', function (evt) {
var e = evt || event;
var code = e.keyCode || e.which;
if (code === 13) { // 13 is the js key code for Enter
$(e.target).trigger('click');
}
});
This will detect a key up event on any a.panel and if it was the enter key will then trigger the click event for the panel element that was focused.