Simulate keyboard with Jquery on button - javascript

I'm trying to experiment some things with js-dos (a plugin of dosbox on browser) and I need a button to simulate a keyboard key (ENTER for example)
I've tried creating an onclick event and inside the function,a Jquery "keypress" event,but nothing seems to work.
I've tried this:
$("button").on("click",function(){
var val=13;
$("canvas").trigger({
type:keypress, keyCode:val,which:val,charCode:val
});
})
and this
var e = jQuery.Event('keydown');
e.which = 13;
e.keyCode = 13;
$("canvas").trigger(e);
What am I doing wrong here?

Add listener to the triggered event.
let e = jQuery.Event('keydown');
$('div').on('keydown', function() {
console.log('calling');
});
$('button').on('click', function() {
$('div').trigger(e);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Lorem Ipsum</div>
<button>Click Me</button>

var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});

Related

is there a function to do on a specific keypress instead of click

i was wondering if there is a function i could use instead of using a mouse click as i have set keybinds to whenever i press it it does it on my pc , here is my code i am using for a broswer script on tampermonkey,
}
$('.pagination.prev').on('click' , function(e){
e.preventDefault();
setTimeout(function(){
getPlayerDataFromSite();
}, 500);
});
$('.pagination.next').on('click' , function(e){
e.preventDefault();
setTimeout(function(){
getPlayerDataFromSite();
}, 500);
});
}
instead of using mouse click on the next button and previous button i would like it to use b key as previous and n key as next
thanks in advance for help really appriciate it
Handling a 'keydown' event is rather simple.
You simply listen for the event, then check for the key you are interested in.
For example, this code listens for the keys "b" and "n":
const pre = document.querySelector('pre');
pre.innerText = "";
window.addEventListener('keydown', event => {
// console.log('keydown event:', event);
pre.innerText += `keydown event.key: "${event.key}"\n`;
if (event.key === 'b') {
alert('You pressed "b"');
} else if (event.key === 'n') {
alert('You pressed "n"');
}
});
document.querySelector('button').onclick = () => {pre.innerText = ""};
<h4>Logging 'keydown' Events</h4>
<button>Clear Log</button>
<pre></pre>
Consideratons
As Stephen P mentions, there are some things to be aware of when using 'keydown' events:
holding a key sends repeated keydown events
non-printing keys such as Shift and Control send keydown events
Shift+N produces uppercase N, not lowercase 'n'

on down arrow KeyPress, click event is getting fired

on down arrow keypress , click event is getting fired, event.keycode is undefined
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
var target = $(this).attr("target");
if (event.keyCode !== '40'){
if (!$(".li-menu").is(":visible") && target === undefined) {
location.href=this.href;
} else {
window.open(this.href, '_blank');
}
}
});
in this code i am trying to open main menu in new tab , but external link is getting open on down arrow keypress
call preventDefault() function.
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
event.preventDefault();
var target = $(this).attr("target");
if(event.keyCode!=='40'){
if (!$(".li-menu").is(":visible") && target===undefined) {
location.href=this.href;
}
else {
window.open(this.href,'_blank');
}
}
});
See the keycode for the reference https://css-tricks.com/snippets/javascript/javascript-keycodes/
in order to configure your app for particular key event
Looking at the classes dropdown-toggle, navbar-collapse, I'm guessing that you are using Bootstrap library.
If that is the case, the behaviour you are seeing is reasonable. Let's break down the issues:
on down arrow keypress , click event is getting fired
Q: You have only bind the handler on click event so why are it is being triggered on keypress?
A: Because this is a feature of bootstrap dropdown. To have better accessibilty, bootstrap triggers click event on the keydown of up, down, esc and space keys.
event.keycode is undefined
Since it is a click event handler and not some keyboard event handler like keydown or keypress, event.keyCode should be undefined
Note: You are using a strict equality in the following condition
if (event.keyCode !== '40')
This will check both the type and value of the operands. Now, event.keyCode always return a Number while '40' is a string, hence the above condtion will yield false even if keyCode is 40. You should correct it to:
if (event.keyCode !== 40)
Now, if you want to stop the redirect on down key, you should check whether the event triggered is an original event or was triggered by some js logic. For this, you may choose jQuery's event.isTrigger or event.originalEvent
Here's a code snippet:
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
var target = $(this).attr("target");
// Check if NOT an triggered event
if (!event.isTrigger) {
if (!$(".li-menu").is(":visible") && target === undefined) {
location.href = this.href;
} else {
window.open(this.href, '_blank');
}
}
});
<a> tags will fire the click event when you press enter on them. However you will not have a keyCode on the event because it is not a Key* event. If you want to know the keyCode add a keyDown or keyUp handler as well. You could also handle both by doing something like the following:
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click keydown", function(event) {
var target = $(this).attr("target");
if(event.type === 'keydown' && event.keyCode!=='40'){
if (!$(".li-menu").is(":visible") && target===undefined) {
location.href=this.href;
}
else {
window.open(this.href,'_blank');
}
}
});
You'll probably also want to add an event.preventDefault(); in there if you wish to prevent default browser behaviour from taking place.

Restore default value of arrows key

I'm using a script (impress.js) that bins some particular action to keyup and keydown events for left, right, up and down arrows.
In some particular moments (for example while typing in a textarea) I want back the default behaviour for the arrows.
I tried without success with
$("a#show-ta").click( function() {
document.addEventListener("keydown", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
document.addEventListener("keyup", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
});
where a#show-ta is the button that shows my textarea.
You want to prevent the keypress from bubbling up to the document where (I assume) Impress binds its handlers:
$("textarea").on('keyup keydown keypress', function(e) {
e.stopPropagation();
});
If you need the event in a specific zone, such as a texarea, you should stop the propagation of the event like this :
$('textarea').keydown( function(ev) {
ev.stopPropagation();
});
If the events are necessary for the whole page but you want to exclude while you are in a textarea, for example, you could raise a flag which you would validate in the event.
var keydownActivated = true;
$('textarea').keydown( function(ev) {
if (keydownActivated) {
ev.preventDefault();
// dostuff
}
});
This will more or less get you where you are going. Create a flag that tracks whether or not the textarea has focus, and check that flag in your current key press event handlers. I can't see all of your code, so this is just a simple example:
var textareaHasFocus = false;
var textarea = document.querySelector('#yourTextarea');
textarea.addEventListener('focus', function(event) {
textareaHasFocus = true;
}, false);
textarea.addEventListener('blur', function(event) {
textareaHasFocus = false;
}, false);
document.addEventListener("keydown", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});
document.addEventListener("keyup", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});

How to fire the actual "Enter" keypress event of the browser?

I know it is possible to use JQuery.Event to simulate "Enter" keypress. Something like this does that -
var event = jQuery.Event( "keydown" );
event.keyCode = 13
$("input").trigger( event );
However, this does not fire the browser default behavior when the actual "Enter" key is pressed. For example, going to next line if the cursor is in textarea or submitting the form when the cursor is in input tag.
I want to know if it is possible to trigger or simulate the actual "Enter" keypress event/behavior.
Try this : Js fiddle
var e = jQuery.Event("keypress");
e.which = 13
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
Do you want some thing similar this one?
$(function(){
$(document).keypress(function(event) {
if(event.which == 13) {
console.log("Dude! You hit Enter Key!!");
}
});
});
you can use this:
$("body").delegate("input", "keypress",function(e){
if(e.which == 13){
}
}
it's work for all input .

Jquery trigger key.Code event

how to trigger keyboard specif key.Code event with jQuery?
I woul like to trigger specifically backspace keyboard event
var e = jQuery.Event("keydown");
e.which = 8; // some value (backspace = 8)
$("input").trigger(e);
<body onkeydown="return inspectKeyCode(event);">
function inspectKeyCode(event)
{
if(event.keyCode == 8){
//Do whatever
//For disabling return false;
}
}
By this you can cancel the backspace button.

Categories

Resources