I am looking for a way to simulate a keyboard press (like the titled suggests). I have looked around and I have found mainly these 2 SO questions:
Is it possible to simulate key press events programmatically?
Simulate keypress without jquery
The issue with those are that they both use the KeyboardEvent.initKeyboardEvent() event which according to MDN it is deprecated. Is there a different way of accomplishing the same thing without that deprecated function?
I would like to know this because I am creating a script for YouTube using Chrome's TamperMonkey extension. This script will, when [space] is pressed, trigger K. K is YouTube's toggle play/pause button. I have the [space] listener working perfectly with the code below:
document.addEventListener("keydown", function(e) {
if(e.keyCode==32) {
e.preventDefault();
}
}, false);
Also I am really looking for a pure JavaScript approach.
If you do this with jQuery you build your event.
https://stackoverflow.com/a/3368599/3257830
If you want to create an event, you initialize the object then dispatch the event.
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
document.addEventListener("keypress", function(e) {
alert(e.which);
});
var e = new Event("keypress");
e.which = 65;
e.keyCode = 65;
document.dispatchEvent(e);
<p id="r">Alerts on event</p>
Related
as the title suggests, I was wondering - what keyboard shortcuts cannot be prevented with javascript in modern browsers? Is this browser-dependent or even system-dependent?
So far, I've got Ctrl+N,Ctrl+Shift+N,Ctrl+T,Ctrl+Shift+T,Ctrl+W,Ctrl+Shift+W, all from Google Chrome. Then there's the standard windows shortcuts with the windows key like the windows key itself, winkey+R, winkey+S, etc., but also Ctrl+Shift+Escape. Is there any way to know what keyboard shortcuts will lead to something javascript can't prevent?
I suppose my question boils down to: if event is a keyboard event, then what does event.preventDefault(); actually prevent?
EDIT
Let's make a list here:
Ctrl+N
Ctrl+Shift+N
Ctrl+T
Ctrl+Shift+N
Ctrl+W
Ctrl+Shift+W
winkey + anything?
Ctrl+Shift+Escape
Ctrl+Alt-Delete (added by Psi)
Alt+F4
Escape and F11 (for fullscreen) (added by zer00ne)
You need to use capturing phase of events to handle and prevent it from default behaviour.
BUT! You cant override CTRL+R, CTRL+W or CMD events in safari.
Better way to prevent user for refreshing page is
window.onbeforeunload = function(event) {}
For example
function preventFn(event) {
if (event.keyCode === YOU_KEY_CODE && event.metaKey) {
event.preventDefault();
event.stopPropagation();
}
}
document.addEventListener('keydown', preventFn, true); // true means use capture phase of event
for example you can use high level library for shortcuts management
hotkeys - powerfull
stack-shortcuts - small and easy
p.s. instead of event.metaKey use what do you need. docs here
There is a website which consists of main frame and some additional ones (they're responsible for parsing inserted data). When I start to edit a record, new frame appears. In the source code I see some JavaScript scripts added. Some of them come from site directories, but also there are some defined in the <head> section of the frame. And there is a function defined, let's call it parseData(input){...}, which is then called upon pressing "Save" link.
Is there any way to assign a keyboard shortcut to execute saving? There are no ids defined for the "Save" link, only href and class.
I tried bookmarklets*, but was stuck on joining the frame URL and the JS function call. Any other ideas?
Edit: * bookmarklets are meant to be launched using Shortcut Manager-like web browser extension.
Edit2: I'm not developing the website. I have read-only access to it.
If you want to use pure javascript to bind, say, "enter" to the function parseData, you could use:
document.onkeydown = function(e){
e = e || window.event;
keycode = e.which || e.keyCode;
if(keycode == 13){ // '13' is the keycode for "enter"
e.preventDefault();
parseData(input);
}
}
You might want to use jQuery with this plugin to create keyboard shortcuts.
Have a look at this:
https://github.com/jeresig/jquery.hotkeys
You may do something like this:
$(document).on('keydown', null, 'ctrl+s', saveFunction);
I am trying to intercept "Hide keyboard button" specific for Ipad in Javascript. I searched everywhere but could not find correct keycode for that.
I pressed any keys and I get a keycode map (for characters, but also for enter, space and delete..).
This is an example of what I want to accomplish
$( "#mydiv" ).on( "keydown", function( event ) {
if (event.which == xx){
//do something
}
}
where xx is my keycode on 'hide keyboard button'. No method is called to the delegate when the button is pressed nor a KeyCode.
I took a look at detect iPad keyboard Hiding button, but I get a solution on a different level (with Xcode), but I need a solution with Javascript.
Hope someone could help.
I found a workaroud for iPad IOS7. I will test on IOS8 to make sure it works. So basically I create a listener on every FOCUSOUT event (for all my texts) and I call my function.
It fires when you have your keyboard open and when you close your "keyboard". It doesn't fire when you select another text field or button, because it targets on null. If you use in combination with keydown, you can save multiple value and call your submit function only when you release your keyboard.
It works for my specific project.
document.addEventListener('focusout', function(e) {
if (e.relatedTarget === null) {
alert("close keyboard without click on something else");
callYourFunction();
}
});
p.s
I'm pretty new here in SO, so I don't know if I can reply myself or I should edit my question or make a comment.
I'm wiriting an Ajax web application with jQuery.
I need to link almost every click event to a keyboard shortcut.
My idea is to use a function like this to bind the events:
$.fn.myclick = function(element, key, customFunction) {
$("body").on("click keypress", element, function (event) {
if (event.keyCode === key || event.keyCode === undefined) {
customFunction();
}
});
};
I'm quite sure this is not a good way and you do know a best way to perform this task.
I think the problem with my method would be that the event could be fired even when I change page and I press the key. I should add some kind of unbind or a way to fire the event only when the user is on the correct page.
The pages are just a list of <section> hidden with display: none; except for the one active.
Any suggestion?
Take a look at js libs for handling keyboard events. Choose any you (or the community) like: http://microjs.com/#keyboard
I need to trigger click on some keypress action, also if it's a up or down key on my keybord script will be removing some class from specify element. So keypress is working but trigger and up down press not, this is my code, ths for help.
$('.main_search_field').keypress(function(evt){
$('.live_search_plugin').addClass('visible');
var scroll_pane = $('.scroll-pane');
scroll_pane.click();
scroll_pane.trigger('click');
if (evt.keyCode == 40) {
$('.live_search_list ul li').removeClass('active');
}
});
You can try following code:
var e = jQuery.Event("keypress");
e.which = 50;
$(".main_search_field").trigger(e);
In e.which put code for required character.
You have to check for the evt keypress like so:
if (evt.which == 40) { }
When using keypress, usually I check for which key I want to interact with before running any code inside my function. If you don't do this, your code will run with any keypress.
.keypress() might not be your best solution here, you could be better off using keydown() and keyup(), or to use the full version: .bind('keydown', handler) (ditto for keyup)
From the jquery docs:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
http://api.jquery.com/keypress/
.click() is shorthand for .trigger("click") and you are using it fine, but do you actually have a click handler on $('.scroll-pane)?
Your code will (assuming browser dependencies) cause two clicks to be triggerred on $('.scroll-pane') and then the if() to be evaluated. But you haven't shown us your click handler for scroll-pane so we can't see if that's at fault.