Say I have this:
<textarea id="myarea">Hello</textarea>
How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8.
And i am not looking for this:
$('#myarea').val( $("myarea").val().slice(0,-1) );
I need to simulate someone actually pressing the 'backspace' key on their keyboard.
Thanks
You can create a keydown event:
var e = jQuery.Event("keydown", { keyCode: 20 });
Then trigger it in your textarea:
$("#myarea").trigger( e );
Update:
After doing some more research and testing, I realize that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key.
To simulate the user going into that textbox and pressing that key, you would have to create a dispatch event
The dispatch event is also not globally supported. Your best bet would be to trigger the keydown event and then update the text area as intended.
I found this:
http://forum.jquery.com/topic/simulating-keypress-events (answer number 2).
Something like this should work, or at least give you an idea:
<div id="hola"></div>
$(function(){
var press = jQuery.Event("keyup");
press.ctrlKey = false;
press.which = 40;
$('#hola').keyup(function(e){
alert(e.which);
})
.trigger(press); // Trigger the event
});
Demo: http://jsfiddle.net/qtPcF/1/
You shouldn't be forcing key events in js. Try simulating the character removal instead.
const start = textarea.selectionStart - 1;
const value = textarea.value;
const newValue = value.substr(0, start) + a.substr(start);
textarea.value = newValue;
Or if you just want the event, instead call the handler directly, rather than forcing the event. This is too hacky.
Related
I am new to javascript, and am writing a simple bookmarklet for a webpage that has a text input section. Basically what I need is a way to execute the following-
if ( ! (text_section).onkeydown ) {
do whatever
}
I need to ignore key-events when the user is typing inside an input field but otherwise trigger key-events for the entire page whenever the user presses a key. I do know that onkeydown is an event listener/handler I'm just trying to explain what I need to do more accurately.
Use an id for your text-section, for example "myTextSection". Apply the addEventListener to the whole document. If the target is anything else, than the textfield, do whatever:
document.addEventListener("keydown", (event) => {
if(event.target !== document.getElementById("myTextSection")){
//do whatever;
}
});
Note that this behaviour might be irritating for users, that navigate by keyboard (for example tab and space keys) through your page. So you might want to add another if statement checking whether the event.keyCode is alphanumeric. In this case the keyCode is in the ranges
[47-58] (for 0-9),
[64-91] (for A-Z) or
[96-123](for a-z)
You should add an event listener to the target element:
targetElement.addEventListener('keydown', (e) => {
// do something
});
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
It is also possible to use onkeydown property:
targetElement.onkeydown = (e) => {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeydown
Using keymaster library for defining and dispatching keyboard shortcuts, I defined shortcut key / to focus input element.
key('/', function() {
$(".topbar input").focus();
});
The issue is that when the / key is pressed, the input is focused with / entered value. I want to get rid of that.
Try this.
key('/', function(event) {
$(".topbar input").focus();
event.preventDefault();
});
It gets focused because you tell it to do so.
Remove this line:
$(".topbar input").focus();
Or give it a function so that you can do stuff when it gets focused
$(".topbar input").focus(function(){
});
I have a code which is suppose to update the number of remaining characters left when the user types in a text input. The code is triggered using keypress event. The problem is the code is triggered only after 2 keypress. Why does that happen?
I have a code to show the key of ASCII code but the character always shows 8 and shows when I press backspace. And how to use String.fromCharCode(event.keycode} ; method.
Why is a event parameter added to a function ?
How does e.keycode know it is displaying the keycode of the user's input.
Code Sample
HTML
<div id="page">
<h1>List King</h1>
<form id="messageForm">
<h2>My profile</h2>
<textarea id="message"></textarea>
<div id="charactersLeft">180 characters</div>
<div id="lastKey"></div>
</form>
</div>
JavaScript
var el; // Declare variables
function charCount(e) { // Declare function
var textEntered, charDisplay, counter, lastkey; // Declare variables
textEntered = document.getElementById('message').value; // User's text
charDisplay = document.getElementById('charactersLeft'); // Counter element
counter = (180 - (textEntered.length)); // Num of chars left
charDisplay.textContent = counter; // Show chars left
lastkey = document.getElementById('lastKey'); // Get last key used
lastkey.textContent = 'Last key in ASCII code: ' + e.keyCode; // Create msg
}
el = document.getElementById('message'); // Get msg element
el.addEventListener('keypress', charCount, false); // keypress -call charCount()
The keypress event is triggered before the input's value is updated, this is why the counter is not up to date. I'd suggest to listen to the input event if you don't need the keyCode. You can also listen to keyup (but the update won't be straight forward) or the combination of keypress and keyup (from "How to get text of an input text box during onKeyPress?", I updated the right answer's fiddle).
Actually, the keypress event doesn't seem to be triggered when you press backspace. That been said, an other solution to ignore "muted" keys ("backspace", "shift", "command" and so on) is to listen to the "input" event (but you won't have access to event.keyCode). Otherwise you can also ignore your code when the keyCode is not relevant.
In regard to String.fromCharCode, simply use String.fromCharCode(event.keyCode) to get the keyCode's "human" equivalent.
The event passed to the function is an object containing all the informations about this given event, including the pressed key.
1) Use 'keyup' insted of 'keypress'.
2) lastkey.textContent = 'Last key in ASCII code: ' + String.fromCharCode(e.keyCode);
3) Don't know much about it. event parameter is added to catch the fired event. It has all the property of the fired event like for 'keyup' it has 'charcode', keycode', 'key' etc.
I have a div that operates as a button. Once the button is clicked, I want it to simulate the pressing of a key. Elsewhere on Stackoverflow, people have suggested using jQuery.Event("keydown"); but the suggestions all use a .trigger() bound to the button as opposed to .click. So, my example code looks like this:
var press = jQuery.Event("keydown");
press.which = 69; // # The 'e' key code value
press.keyCode = 69;
$('#btn').click( function() {
$('#testInput').focus();
$(this).trigger(press);
console.info(press);
});
I've set up a dummy example at JSFiddle:
http://jsfiddle.net/ruzel/WsAbS/
Eventually, rather than have the keypress fill in a form element, I just want to register the event as a keypress to the document so that a MelonJS game can have it.
UPDATE: It looks like triggering a keypress with anything other than the keyboard is likely to be ignored by the browser for security reasons. For updating a text input, this very nice Jquery plugin will do the trick: http://bililite.com/blog/2011/01/23/improved-sendkeys/
As for anyone who comes here looking for the solution in the MelonJS case, it's best to use MelonJS's me.input object, like so:
$('#btn').mousedown(function() {
me.input.triggerKeyEvent(me.input.KEY.E, true);
});
$('#btn').mouseup(function() {
me.input.triggerKeyEvent(me.input.KEY.E, false);
});
I'm not sure why, but even though this is triggering the event correctly, it doesn't fill the input with the character.
I've modified the code to show that the document is indeed receiving keypress events when we say $(document).trigger(p)
Try it out:
http://jsfiddle.net/WsAbS/3/
var press = jQuery.Event("keydown");
press.which = 69; // # Some key code value
press.keyCode = 69;
press.target = $('#testInput');
$(document).on('keydown', function(event) {
alert(event.keyCode);
});
$('#btn').click( function() {
$(document).trigger(press);
});
I believe this should be good enough for your end goal of a MelonJS game picking up keypresses.
If you want a virtual keyboard (As the title suggests) you can use this one.
I want to send keystrokes on the selected element like this:
$(":input").click(function(){
$(this).trigger("keydown", [{
preventDefault:function(){},
keyCode:9,
shiftKey: true
}]);
});
//wants to send Shift+Tab keystroke on input click
Demo: http://jsfiddle.net/NYwCT/.
You cannot send keystrokes. It currently triggers any functions that are bound, but does not execute the relevant thing at browser level (what about a script sending ALT+F4?).
If you want to focus the input before the clicked one, you can use .prev() (previous sibling): http://jsfiddle.net/NYwCT/1/.
$(":input").click(function(){
$(this).prev().focus();
});
This will not fire the actual event
var press = jQuery.Event("keypress");
press.shiftKey = true;
press.keyCode = 9;
$(this).trigger(press);
you could also try this plug-in: fn.sendkeys or jwerty