I'm making a system where you press a key and it changes text box. I only want to be able to put the values X, x, E, e, /
My current jQuery code is
$('.today').keyup(function(e) {
var self = $(this);
var currentInput = self.data('number');
var next = $(currentInput + 1);
var previous = $(currentInput - 1);
var keyCode = e.keyCode || e.which;
var num = self.data('number') + 1;
var nom = self.data('number') - 1;
if(('input.today[data-number="' + num +'"]').length && keyCode === 40)
$('input.today[data-number="' + num +'"]').focus()
else if(('input.today[data-number="' + nom +'"]').length && keyCode === 38)
$('input.today[data-number="' + nom +'"]').focus();
else if(('input.today[data-number="' + num +'"]').length && self.val().length == self.attr('size')) {
$('input.today[data-number="' + num +'"]').focus();
}
});
I only want the focused box to move if the key up is one of these: X, x, E, e, /, UP, DOWN, LEFT, RIGHT. And if the values are not X, x, E, e, / then to not write in the box
This might help:
$('.today').keyup(function(e) {
if(~[38, 39, 40, ...].indexOf(e.keyCode || e.which)) {
e.preventDefault();
return;
}
...
}
The key there being the call to e.preventDefault().
You also have of the element the keyup event originated in as e.target.
HTH
You can examine the key that was pressed to determine how the event should proceed. If you don't want text to appear on certain key presses, then you can either return false from the handler, or call e.preventDefault():
if ($.inArray(e.keyCode, [69, 88, 191]) === -1) { // e, x, / respectively
e.preventDefault(); // don't print the character
}
You can get a list of the JavaScript keycodes here: Key Codes.
Related
Similar to this solution how can I re-use the code to include both keyDown and keyUp events? I added one even for each KeyUp and KeyDown but there are problems when user holds down and releases a key and the events from the original keyUp event no longer continuously fire.
Example:
User presses and holds down Ctrl + Shift so KeyDown is continuously fired and prints Ctrl + Shift is pressed.
User releases Shift while still holding Ctrl so KeyUp is fired once but KeyDown for Ctrl no longer continue to fire
How can I improve this? The aim is to pair this with a mousescrollwheel event. If ctrl+mousewheel then scale plot along x axis. If Alt+moussewheel then scale along ploy Y axis. If both or neither then scale X and Y. Lastly, how can I pair this key modifier event with the mouse scroll wheel I provided to be in a responsive manner? I notice there are times where the key events will block the scroll event.
var scrollDelta = 0;
$(document).on("keydown", reportKeyEvent("Pressed") );
$(document).on("keyup", reportKeyEvent("Released") );
$(document).bind("wheel", updateScroll);
function reportKeyEvent (e, eventName) {
var keyStr = ["Control", "Shift", "Alt"].includes(e.key) ? "" : e.key + " ";
var out =
eventName + " " +
( e.ctrlKey ? "Control " : "" ) +
( e.shiftKey ? "Shift " : "" ) +
( e.altKey ? "Alt " : "" ) +
keyStr + "key(s)"
;
console.log(out)
ctrlKeyPressed = e.ctrlkey;
shiftKeyPressed = e.shiftkey;
altKeyPressed = e.altkey;
// add shift+scroll?
// add ctrl+scroll?
e.stopPropagation ();
e.preventDefault ()
}
function updateScroll(e){
if(e.deltaY < 0){
scrollDelta +=50;
}else if (e.delaY > 0){
scrollDelta -=50;
}else{
scrollDelta = 0;
}
}
You can keep your reportKeyEvent function. Just change to use the interval instead of the event
var keydownIntervalID;
var keys = new Set();
$(document).keyDown(function(e) {
keys.add(e.keyCode);
if (!keydownIntervalID) {
keydownIntervalID = setTimeout(reportKeyEvent, 50);
}
});
$(document).keyUp(function(e) {
keys.delete(e.keyCode);
if (keys.size === 0) {
clearInterval(keydownIntervalID);
keydownIntervalID = undefined;
}
});
I'm trying to make a hotkey for a web app, for example Ctrl + z performs the undo function.
It seems that when I press the keys fast (as I'm used to from using desktop apps a lot), it doesn't register. The single key press registers, but it misses the combination for some reason.
From what I understand, you have to keep track of which buttons are held down via keypress events, which is what I've done below.
Try the code below. Hitting Z outputs Z. Hitting CTRL then Z slowly outputs CTRL + Z. Hitting CTRL then Z quickly outputs Z. When I perform the action at the same speed in say Notepad for windows, it works flawlessly almost every time.
https://codepen.io/samkeddy/pen/YQjgdZ?editors=1010#0
var ctrlPressed=false, altPressed=false;
window.addEventListener("keydown", function (e) {
hotkey = e;
if (e.keyCode == 17) ctrlPressed = true;
if (e.keyCode == 18) altPressed = true;
e.preventDefault();
});
window.addEventListener("keyup", function (e) {
hotkey = window.event;
if (e.keyCode == 17) ctrlPressed = false;
if (e.keyCode == 18) altPressed = false;
if (e.keyCode == 90){
if (altPressed && ctrlPressed && e.keyCode == 90)
addText('ALT + CTRL + Z');
else if (ctrlPressed && e.keyCode == 90)
addText('CTRL + Z');
else
addText('Z');
}
});
//meaningless, just adds text to doc so you can see it
function addText(text) {
var theDiv = document.getElementById("output");
theDiv.appendChild(document.createElement("br"));
var content = document.createTextNode(text);
theDiv.appendChild(content);
}
Use e.ctrlKey to check if ctrl is down instead of variables, and just check for the hotkey combination on keydown, don't do anything on key up.
https://codepen.io/samkeddy/pen/gRdBpq
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90 && evtobj.ctrlKey) addText("CTRL + Z");
else if (evtobj.keyCode == 90) addText("Z");
}
document.onkeydown = KeyPress;
In my code below, the problem I have is that the focusPosition function is called but the console does not log the desired string: ("shift + left/right arrow")
// Hold reference to the currently focused position
var currentPosition = 0;
// Maximum position we can navigate to is the last item in the summary list
var maxFocusablePosition = summaryList.length - 1;
// Utility function to focus a given position value
function focusPosition(position) {
console.log("focus position is called");
$('#' + summaryList[position]).focus();
};
// Focus the first one by default
focusPosition(currentPosition);
$(document).keydown(function (event) {
if (event.which === 37 && event.which === 16) {
currentPosition = (currentPosition > 0) ? parseInt(currentPosition) - 1 : maxFocusablePosition;
console.log(' shift + left');
}
if (event.which === 39 && event.which === 16) {
currentPosition = (currentPosition < maxFocusablePosition) ? parseInt(currentPosition) + 1 : 0;
console.log('shift + right');
}
focusPosition(currentPosition);
});
Look for the arrow key in which, and look for event.shiftKey being truthy to know whether the shift key is down. That's how modifier keys work with the keydown event (there's shiftKey, ctrlKey, altKey, and metaKey).
i am creating a system where there will be a pacific mobile view. From this you will be able to press one of 3 buttons and it will emulate a key press on a keyboard.
Currently for the desktop version the focused box changes like this:
$('.today').keydown(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191, 8, 40, 38]) === -1) { // 8 is backspace
e.preventDefault();
}
});
$('.today').keyup(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191, 8, 40, 38]) === -1) { // e, x, / respectively // don't print the character
return false;
}
var self = $(this);
var currentInput = self.data('number');
var next = $(currentInput + 1);
var previous = $(currentInput - 1);
var keyCode = e.keyCode || e.which;
var num = self.data('number') + 1;
var nom = self.data('number') - 1;
if(('input.today[data-number="' + num +'"]').length && keyCode === 40)
$('input.today[data-number="' + num +'"]').focus()
else if(('input.today[data-number="' + nom +'"]').length && keyCode === 38)
$('input.today[data-number="' + nom +'"]').focus();
else if(('input.today[data-number="' + num +'"]').length && self.val().length == self.attr('size')) {
$('input.today[data-number="' + num +'"]').focus();
}
});
For the buttons I have this piece of code:
$("button").click(function() {
$(".today").focus();
var e = jQuery.Event("keydown");
e.which = 47; // # Some key code value
$("input").val(String.fromCharCode(e.which));
$("input").trigger(e);
});
$('input').keypress(function(e){
console.log('Yes keydown triggered. ' + e.which)
});
This fills the text box and it will change to next, but then when i press it will focus back to original... Any ideas.
$(".today").focus();
suggests your using classes as the identifier, are your ID's unique?
I call
element.focus();
Where element is HTMLInputElement of type=button.
But then the browser clicks the button! That's in mozilla and chrome.
How do i highlight the button with selection, but not initiate the click event?
No .focus() doesn't click the button or submits the form: http://jsbin.com/onirac/1/edit
It does exactly what you want it to.
Well, i've identified the reason.
I was handling the onkeydown event for Enter key.
The solution is to use
e.preventDefault();
function ConvertEnterToTab(s, e, numSkipElements) {
var keyCode = e.keyCode || e.htmlEvent.keyCode;
if (keyCode === 13) {
var tabIndex = s.tabIndex || s.inputElement.tabIndex;
if (numSkipElements == undefined) {
numSkipElements = 0;
}
var nextElement = FindNextElementByTabIndex(tabIndex + numSkipElements);
if (nextElement != undefined) {
nextElement.focus();
return e.preventDefault ? e.preventDefault() : e.htmlEvent.preventDefault(); // this is the solution
}
}
}
function FindNextElementByTabIndex(currentTabIndex, maxTabIndex) {
if (maxTabIndex == undefined) {
maxTabIndex = 100;
}
var tempIndex = currentTabIndex + 1;
while (!$('[tabindex='+ tempIndex+ ']')[0] || tempIndex === maxTabIndex) {
tempIndex++;
}
return $('[tabindex=' + tempIndex + ']')[0];
}