jQuery keypress() event not firing? - javascript

I am trying to fire an event on the right and left arrow key presses with jQuery. Using the following code, I can fire events on any of the alphanumeric keys, but the cursor keys (up, down, left, right) fire nothing. I am developing the site primarily for IE users because it is a line of business app. Am I doing something wrong here?
$('document').keypress(function(e){
switch (e.which) {
case 40:
alert('down');
break;
case 38:
alert('up');
break;
case 37:
alert('left');
break;
case 39:
alert('right');
break;
default:
alert('???');
}
});

e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.

With jQuery, I've done it this way:
function checkKey(e){
switch (e.keyCode) {
case 40:
alert('down');
break;
case 38:
alert('up');
break;
case 37:
alert('left');
break;
case 39:
alert('right');
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keypress (checkKey);
} else {
$(document).keydown (checkKey);
}
Also, try these plugins, which looks like they do all that work for you:
http://www.openjs.com/scripts/events/keyboard_shortcuts
http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

You have the word 'document' in a string. Change:
$('document').keypress(function(e){
to
$(document).keypress(function(e){

Ofcourse this is a closed issue, i would like to add something to your discussion
In mozilla i have observed a weird behaviour for this code
$(document).keydown(function(){
//my code
});
the code is being triggered twice. When debugged i found that actually there are two events getting fired: 'keypress' and 'keydown'. I disabled one of the event and the code shown me expected behavior.
$(document).unbind('keypress');
$(document).keydown(function(){
//my code
});
This works for all browsers and also there is no need to check for browser specific(if($.browser.mozilla){ }).
Hope this might be useful for someone

Your original code has $('document')... when it should have $(document) without the quotes.

Related

Looking for a date widget operated by up and down arrow keys to increment date

I know some calendar widgets, but they do more than I need.
All I want is a text field with todays date and the ability to add or subtract a day by hitting the up or down arrow keys.
I know the keycodes 40 for down and 38 for up, and the onkeydown event, but don't know enough to put this together to have a functioning field. I thought to start like this:
<input type="text" value="<?php echo date('d.m.Y',mktime(date('H'))); ?>" onkeydown="keydownFunction()">
<script type="text/javascript">
function ArrowFun() {
switch (window.event.keyCode) {
case 38: ... +1 day
break;
case 40: ... -1 day
break;
}
}
</script>
Is there possibly a widget which does this already (I don't want a calendar popping up though)? I would go with a widget that has mouse operated arrow icons which lead to the same functionality as well.
Any help is greatly appreciated.
Using MomentJS and jQuery
$(function() {
var now = moment(); //Makes now a new moment, you could feed this the PHP date if needed as well...
$('#dateBox').val(now.format('D.M.YYYY')); //Formats the date
$('body').keydown(function(e) { //You can update the selector to #dateBox to refine it.
switch(e.which) {
case 38: // up
$('#dateBox').val(now.add(1,'Day').format('D.M.YYYY'));
break;
case 40: // down
$('#dateBox').val(now.subtract(1,'Day').format('D.M.YYYY'));
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
JSFiddle
You can use this library, there is very useful methods to do that.

Is it possible to add cases to switch statement in javascript?

My question divide in three questions:
1.Is it even possible ?
2.If yes can we do it with the default value ?
3.Or could with do it outside the switch statement ?
Example for questions 2:
switch(stuff) {
case 'something':
some event;
break;
case 'the case that could be add by the default element':
some event that could happen only after the code was executed
default:
magic code that would add another case element
}
Example for question 3:
switch(stuff) {
case 'something':
some event;
break;
case 'the case that could be add by the magic code':
some event that could happen only after the code was executed
default:
some default event
}
magic code that would be executed after the switch and that would add a case
You can't really code JavaScript so that it will modify itself, but you can code a switch statement such that certain cases will be ignored initially and then "turned on" later:
var enableCase = false;
switch(true) {
case stuff === 'something':
// some code;
break;
case enableCase && stuff === 'the case not initially enabled':
// some code
break;
default:
// turn on previous case:
enableCase = true;
break;
}
Having said that, I don't really recommend doing it. There is almost certainly a more sensible way to implement this depending on the underlying problem you are trying to solve. Perhaps with an if/if else/else block that tests a flag set elsewhere.

jQuery Prevent Default - doesn't appear to work in some circumstances

I have used event.preventDefault() and event.stopPropagation() in various places but it always seems to be a bit of a struggle to get it to work.
I have now hit a wall with the instance:-
$("#existing_Flavours").on("keydown", function(event){
switch(event.which){
case 9:
//tab called permit
break;
default:
event.preventDefault();
event.stopPropagation();
} // end switch
});
I want the tab key to work but nothing else.
Been round this endlessly and no matter what I cannot stop normal key strokes from occurring.
If the element is dynamic you'll need to delegate the event to an element that actually exists when binding the keydown :
$(document).on("keydown", "#existing_Flavours", function(event){
switch(event.which){
case 9:
//tab called permit
break;
default:
//event.preventDefault();
//event.stopPropagation();
// or just use return false
return false;
}
});​
My guess is it has to do with which events actually cause a character to appear. I would try binding to keydown keyup keypress to make sure you catch all of them.
well, first of all, i dont like the switch to much (probably this has nothing to do), try:
$("#existing_Flavours").live("keydown", function(event){
var keyCode = event.keyCode || event.which;
if (keyCode != 9) {
event.preventDefault();
}
});

switch statement not working, only first case triggers actions

I'm new to writing switch statements after learning about it yesterday.
For some reason, this isn't working.
checkCase(2);
checkCase(1);
checkCase(0);
function checkCase(priorityType){
switch(priorityType){
case 2:
print(priorityType);
break;
case 1:
print(priorityType);
break;
case 0:
print(priorityType);
break;
}
}
The 'alert(2)' is triggered, 1 and 0 are not.
I've reversed the case 2: with case 1: and run the code again and 2 is once again triggered, 1 is not.
I've also tried adding break; and continue; to the cases, but still nothing.
Why is that? what have I done wrong?
----------------------EDIT---------------------------
Lots of responses saying that I need to add 'break;' which I've now done to each line.
Still no output. I've also changed 'alert' to 'print'. No difference.
-------------edit2-----------------------
my bad, the 'break' is working now. not sure what was going on when I checked last. Maybe needed to restart ff.
You must break; after each case.
function checkCase(priorityType){
switch(priorityType){
case 2:
alert(priorityType);
break;
case 1:
alert(priorityType);
break;
case 0:
alert(priorityType);
break;
//my two cents
default:
alert("No intended code for"+priorityType);
}
}
checkCase(2);
checkCase(1);
checkCase(0);
Two problems: Debugging using alert is problematic and you need break statements.
Try adding breaks and using print in the square free shell, and I think you'll see the proper result.
checkCase(2);
checkCase(1);
checkCase(0);
function checkCase(priorityType){
switch(priorityType){
case 2:
print(priorityType); break;
case 1:
print(priorityType); break;
case 0:
print(priorityType); break;
}
}
Because there are no break statements, once a matched case is found, it and the subsequent cases will fire.
So when you do:
checkCase(2);
You'll get:
alert(2);
alert(2);
alert(2);
When you do:
checkCase(1);
You'll get:
alert(1);
alert(1);
When you do:
checkCase(0);
You'll get:
alert(0);
If you were hoping to get:
alert(2);
alert(1);
alert(0);
You'd need to change your switch to include break; statements.
function checkCase(priorityType){
switch(priorityType){
case 2:
alert(priorityType);
break;
case 1:
alert(priorityType);
break;
case 0:
alert(priorityType);
break;
}
}

Writing a custom text box for web pages

I want to capture user's activities on my textbox. Since a normal textbox won't give me enough information on what my user is doing currently with it, I want to start on a custom HTML text box.
For e.g.
If my user is typing
Hello world! (Say he made a typo...) I should be able to tell him that,
H e l l o w o r l e [bksp] d !
also if a user selects a text, I should be notified about it.
P.S. I've mentioned a custom text box inorder to be generic. If I can make use of / create something like a plugin on the already available text box or say even a javascript, it's fine.
Your best bet would be to add functionality to the existing <input type="text"> using javascript.
I don't know how you would create your own textbox as browsers just interpret html which only contain the predefined elements in the HTML specification (apart from certain exceptions such as ActiveX).
As a solution regarding to what you want you can capture every keypress using the onKeyUp event of your document. You can catch every keypress and display them to your liking.
small example:
<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck()
{
var keyID = event.keyCode;
var keypressed;
switch(keyID)
{
case 16:
keypressed = "Shift";
break;
case 17:
keypressed = "Ctrl";
break;
case 18:
keypressed = "Alt";
break;
case 19:
keypressed = "Pause";
break;
case 37:
keypressed = "Arrow Left";
break;
case 38:
keypressed = "Arrow Up";
break;
case 39:
keypressed = "Arrow Right";
break;
case 40:
keypressed = "Arrow Down";
break;
}
document.write(keypressed);
}
</script>
for a list of all the keycodes see here.
[Update]
I just saw that you are also want to know when someone selects text and luckily for you there are also events that handle this:
An <INPUT TYPE = "text"> aswell as a <TEXTAREA> have an .onSelect event which you can capture. Then you can get the selected text using the method you find on this other StackOverflow Question: How to get selected text from textbox control with javascript
If you are working heavily in javascript I suggest you take a look at JQuery (if you haven't already). It will definitely make your life easier.

Categories