jQuery Keyboard Function keyPress - javascript

I have the following HTML/CSS to create a simple keyboard. I have tried experimenting with jQuery keyPress(), yet I can't seem to get it so while you are pressing a key on the keyboard, the corresponding letter has the class 'trigger'.
For example, when you press Q in the textarea with id 'input', the span with id 'q' should change its background to the color green (to the class 'trigger')
Any help would be much appreciated, thanks in advance.
EDIT
So far I have some Javascript, that alerts on each keystroke. See this example

If you want the background to change only while the key is down you need to set it on keydown and set it back on keyup:
$(function () {
$("#input").keydown(function (event) {
$("#" + String.fromCharCode(event.which)).addClass("trigger");
}).keyup(function (event) {
$("#" + String.fromCharCode(event.which)).removeClass("trigger");
});
});
Note that keydown and keyup return key codes not character codes, but as far as the alphabet keys go it is safe to treat them as if they were character codes for the uppercase letters. (So in the following demo I've changed the ids of the spans to be uppercase to save doing arithmetic in the event handlers.)
Demo: http://jsfiddle.net/AHPaY/6/
P.S. If you experiment with the demo you'll see this works for simultaneous keypresses too, e.g., hold down Q and T at the same time...

On the keypress event, the event.which property maps to a character code. The String.fromCharCode method can be used to convert the numeric charcode to a character.
In the example, a regular expression is used to check whether the single character is a valid code. If yes, then a class is added.
Demo: http://jsfiddle.net/AHPaY/4/
$(function () {
$("#input").keypress(function (event) {
$('.trigger').removeClass('trigger');
var char = String.fromCharCode(event.which).toLowerCase();
if (/[qwerty]/.test(char)) {
$('#'+char).addClass('trigger')
}
});
});

Try this
$(function () {
$("#input").keypress(function (event) {
var keycode=event.which || event.keycode;
var key=String.fromCharCode(keycode).toLowerCase();
$('span.trigger').removeClass('trigger').addClass('key'); // reset
$("#"+key).removeClass('key').addClass('trigger');
});
});
A fiddle is here.
Another fiddle is here.
If you want to leave all the spans green then disable the line commented with reset.

Related

How to disable all keys in key board except tab key

How to disable all keys in key board except tab key for select box in html. Can any one provide the code for this one?
Below is i tried below code but it was not working
I hope this will help you..put textbox and selectbox in the page..
document.getElementById("li1").onkeydown = function (e) {
e.preventDefault();
}
Demo
I don't know what you want to do exactly, but if you use jQuery this is fairly simple:
$('html, body').keydown(function(event){
if(event.keyCode !== 9) { // 9 = tab
event.preventDefault();
}
});
If you want to disable keys only when a given element has focus, you can change the selector inside $().

Prevent typing spaces in an HTML text box with jQuery

So I've got an HTML form that users can type in. How can I use javascript/jQuery to immediately and seamlessly remove spaces from a text box when one is put in? I've been researching the .val() jQuery method and came up with this:
$('input').keydown(function() {
str = $(this).val();
str = str.replace(/\s/g,'');
$(this).val(str);
});
That does weird things to removing text and the spaces still show up on keystroke, they just get removed on the following keystroke. Any suggestions?
You could prevent it from being added at all by checking whether the key pressed is the space bar and returning false if so:
​$("input").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
Here's a working example.
Try use keyup
Live Demo
$('input').keyup(function() {
str = $(this).val();
str = str.replace(/\s/g,'');
$(this).val(str);
});

Can i simulate a key press? [duplicate]

Using jQuery, how can I simulate (trigger?) a KeyPress when a link is clicked? For example, when a user clicks the following link:
<a id="clickforspace" href="#">Click Here</a>
Then, by clicking the link, it would be as if they pressed the "spacebar" on their keyboard.
Something like this, I'm assuming:
$("#clickforspace").click(function(e) {
e.preventDefault();
//... Some type of code here to initiate "spacebar" //
});
Any ideas on how to achieve this?
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
http://api.jquery.com/trigger/
The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.
http://docs.jquery.com/Events/trigger#eventdata
Read the above documentation for more details.
You could try this SendKeys jQuery plugin:
http://bililite.com/blog/2011/01/23/improved-sendkeys/
$(element).sendkeys(string) inserts string at the insertion point in
an input, textarea or other element with contenteditable=true. If the
insertion point is not currently in the element, it remembers where
the insertion point was when sendkeys was last called (if the
insertion point was never in the element, it appends to the end).
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);

Javascript Events: How to trigger event when ALT+NUM character is entered

I first used the onKeyUp event to detect input changes in a textbox. However, when the user enters in a French character using ALT+Num, the event doesn't detect the change until i enter the next character...
Which event should I be using to detect the special character changes. I've tried onChange but does not seem to be working.
I've tried using onkeypress event because I notice that it triggers it after i release the ALT key, however even though once the ALT is release, the onkeypress is triggered and you see the accented character, but when I use this.value for the inputbox, it only registers up to and before the new ALT+Num character is input.
for example: i entered vidé, but the search would not dynamically find vidé, but only vid because the é has not been saved in the - this.value yet, until another key event is triggered.
Hence I was wondering if there's way to simulate/send a key press to trigger it.
FINALLY FIGURED IT OUT!! :D
here's the code, however the String converting event.which code does not work on the jsFiddle though, nonetheless the code works :)
$('#i').keydown(function() {
document.getElementById('j').value = "down";
$('#k').val($('#i').val())
});
$('#i').keyup(function() {
document.getElementById('j').value = "up";
$('#k').val($('#i').val())
});
$('#i').keypress(function(event) {
$('#k').val(String.fromCharCode(event.keycode));
});
$('#i').change(function() {
document.getElementById('j').value = "change";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="i" type="text" /><br />
<input id="j" type="text" />
<input id="k" type="text" />
View on JSFiddle
use keyup. The new character will not be added until the user releases the ALT key and at that point the keyup event will fire.
There's a reference at http://unixpapa.com/js/key.html which might be a good idea to have a look at, and according to section 2.1, ALT should generate a keydown and keyup in modern browsers..
I would suggest you use jQuery or a similar library to ease the issues you're facing cross-browser. Have a look at http://jsfiddle.net/qvDbu/1/ for a proof of concept which works fine.
Keypress is not triggered by only modifier-presses, so that's probably the way to go, it allows you to pick up the character entered as well, rather then which key is pressed. Edit: Seems to not be the case in Fx that keypress is triggered by modifiers, but I'm not able to reproduce actually loosing any characters.
The character entered with the ALT+NUM combination will only be added to the input element's value after the keyup event triggers, so you won't be able to read it in that event handler.
In order to solve this problem you could set a timeout on the ALT keyup event before reading the input element's value:
$('input').on('keyup', function (e) {
var _this = this;
var ALT_KEY_CODE = 18;
if (e.which == ALT_KEY_CODE) {
setTimeout(function () {
handleKeyup.call(_this , e);
}, 1);
} else {
handleKeyup.call(_this , e);
}
});
function handleKeyup (e) {
// $(this).val() now holds the ALT+NUM char
}
You need to bind onkeypress, which won't fire until you finish entering the alt code.
document.getElementById('input').onkeypress = function() {
alert('fired');
}
<input id='input' type='text' />
View on JSFiddle

Simulate Keypress With jQuery

Using jQuery, how can I simulate (trigger?) a KeyPress when a link is clicked? For example, when a user clicks the following link:
<a id="clickforspace" href="#">Click Here</a>
Then, by clicking the link, it would be as if they pressed the "spacebar" on their keyboard.
Something like this, I'm assuming:
$("#clickforspace").click(function(e) {
e.preventDefault();
//... Some type of code here to initiate "spacebar" //
});
Any ideas on how to achieve this?
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
http://api.jquery.com/trigger/
The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.
http://docs.jquery.com/Events/trigger#eventdata
Read the above documentation for more details.
You could try this SendKeys jQuery plugin:
http://bililite.com/blog/2011/01/23/improved-sendkeys/
$(element).sendkeys(string) inserts string at the insertion point in
an input, textarea or other element with contenteditable=true. If the
insertion point is not currently in the element, it remembers where
the insertion point was when sendkeys was last called (if the
insertion point was never in the element, it appends to the end).
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);

Categories

Resources