How can I simulate a keypress in JavaScript? [duplicate] - javascript

This question already has answers here:
Jquery script for simulated key press down not running keyboard shortcut
(2 answers)
Closed 6 years ago.
I'm trying to find a way to simulate a keypress.
For example, when function launched, the key "Arrow Down" should be pressed and so the webpage should be slightly scrolled.
I'm interested only in Chrome, and both jQuery or plain JS will be appropriate. (Plain JS will be more preferable).
That's one of the code examples I tried:
var e = $.Event("keydown", { keyCode: 40}); // 40 = down arrow
$("body").trigger(e);
// When I launch it the console, nothing happens. The page is not scrolled.
// May be I missed some obvious?
I searched and found the following related questions, but the solutions did not work for me:
Definitive way to trigger keypress events with jQuery
Firing a Keyboard Event in JavaScript
How to trigger event in JavaScript?
Simulate left and right arrow key event with javascript
Simulate Keypress With jQuery
Simulating a Keypress Event from Javascript Console
Simulate JavaScript Key Events
In other words
Using AutoHotkey, you can easily make something like:
Down::
Send, {Up}
Then, if you press Down arrow key, it will be triggered Up. I just want to implement it with JS.

As #rfsbsb pointed out from: Jquery script for simulated key press down not running keyboard shortcut
If you're trying to fire some browser or system wide keyboard shortcut
then it's a dead end - it can't be done for security reasons. If it
would be possible, you would have pages all over the Internet that
would (for example) add themself to your bookmarks without even asking
(by firing CTRL+B shortcut using Javascript).

Using this answer, I managed to change the code a bit and I think I got what you are looking for?
here is my jsfiddle
Code:
jQuery(document).ready(function($) {
$('body').keypress(function(e) {
if(e.which == '40')
$('body').animate({scrollTop: '100px'});
});
});
jQuery.fn.simulateKeyPress = function(character) {
jQuery(this).trigger({
type: 'keypress',
which: character
});
};
setTimeout(function() {
$('body').simulateKeyPress(40);
}, 1000);

Here is a sample starting from #Haring10's example:
https://jsfiddle.net/po33vfb4/4/
$('body').keydown(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if(e.which == 40) {
window.scrollBy(0, -100);
} else {
window.scrollBy(0, 100);
}
});
Triggering keydown-keyup-keypress programatically does not seem to have the efect of scrolling. The above sample can be customized to add animations.

Related

Phonegap Android show keyboard on input focus Javascript

I have been searching for how to trigger the android keyboard via Javascript.
I have found a few answers but none of them seem to work.
One solution is here:
Showing Android's soft keyboard when a field is .focus()'d using javascript
On the example above there is a button involved which I don't have, but do I need it?
I am using 'tap' and 'swipe' events via the touch-layer.js which seems to disable click events in favour of tap. (https://github.com/cubiq/touch-layer)
Below is the code I've tried, the alert triggers and the focus happens but the keyboard doesn't show.
gt("#txtEmail").on("tap", function() {
alert('tap');
$(this)[0].el[0].focus();
$("#txtEmail").trigger('click');
});
Thanks.
EDIT 1: Second attempt doesn't work even though this seems more inline with the example.
gt("#txtEmail").on("tap", function() {
alert('trigger');
$("#txtEmail").trigger('click');
});
$("#txtEmail").on("click", function() {
alert('recieved');
$(this).focus();
});
In addition to Jack He's suggstion, check out ionic-plugin-keyboard. This one is more actively maintained and used by many.
In my case, I just bound focus event to a handler function that manually shows the keyboard.
$(".my-input").on("focus", function(e) {
...
cordova.plugins.Keyboard.show();
...
});
What you need is the SoftKeyBoard plugin. Just check the link to find what you want.

Keyup to Manipulate div

Haven't post in quite a while.
Anyway I was searching about my subject and I got this.
$(window).keyup(function(e) {
if (e.which === 8) {
$('.ilol'). fadeOut();
}
});
It's working perfectly fine. But when I change the window to a class or id it doesn't respond anymore.
There's not a lot of detail about the type of element you are trying to attach this event handler to, but the jQuery documentation explains that form elements (e.g. input) are a safe bet because they are able to be focused across most browsers:
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus. Focusable elements can vary
between browsers, but form elements can always get focus so are
reasonable candidates for this event type.
http://api.jquery.com/keyup/
It may also be a selector issue. Make sure that your selector is working properly by pasting it in your browser's JavaScript console and see if it returns any elements.
Make sure you are binding event in ready function.
$(document).ready(function(){
$('.someClassName').keypress(function(e) {
if (e.keyCode === 8) {
$('.ilol'). fadeOut();
}
});
});
After some testing this is what worked best for me. The 40 key in this example is the down arrow key.
$(document).keydown(function(e)
{
if(e.keyCode == 40){
$('.ilol').fadeOut('fast');
}
});

How Google Doc intercepts Ctrl - S / Command - S to save the document not the html page

I am trying to introduce this into my project, I did some search but here https://github.com/RobertWHurst/KeyboardJS/issues/19 I found that it looks quite hard to intercept these meta keys.
So I am curious how google doc does that? Is it a different way from using just javascript?
It's not difficult at all. You just bind to document and listen for keydown: http://jsfiddle.net/zerkms/DVmDs/ (just assume your document is the bottom right block and click it once before you press ctrl+s)
$(document).on('keydown', function(e) {
if (e.keyCode == 83 && e.ctrlKey) {
alert('you have pressed ctrl+s');
}
});​
What have you tried?
Here's a fiddle (that I found in google, took me about 10 seconds) that is intercepting those events using common methods:
http://jsfiddle.net/GBuBj/
taken from here: http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/
and here: https://superuser.com/questions/120672/mediawiki-assign-ctrl-s-to-save-page-edit-mode
Win key is different story, but CTRL is fine (except maybe CTRL+ESC and couple of similar shortcuts that are used by OS).

Will this JavaScript code affect other keypress events too by disabling one key?

I'm using this to disable the 'scrolling' effect the spacebar has in a browser. Will this affect other keypress events too?
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
Could someone please explain what this is doing? I'm not sure if this code is bad, but it seems to disable other keypress related codes in my page, and I want to make sure this isn't the reason.
Thanks!
ASCII code 32 is the ASCII value that represents the spacebar key, and your code is essentially telling the browser to return false whenever that keycode is detected. Since false is returned, the scrollbar effect you speak of is in fact successfully disabled.
However, the unfortunate side effect of this convenient spacebar-scroll-disabling function is that it disables spacebar keypresses everywhere on the page.
Instead of returning false, if the keycode is detected, pass the current scrollTop value into a closure that returns a function to a setTimeout event. When the setTimeout fires, the scrollTop position is reset back to the value it was in when the setTimeout event was first registered.
window.onkeydown = function(e) {
if(event.keyCode == 32) { // alert($(document).scrollTop() );
setTimeout(
(function(scrollval) {
return function() {
$(document).scrollTop(scrollval);
};
})( $(document).scrollTop() ), 0);
}
};
Your users can still conveniently make use of spacebars in input textboxes and textareas, and at the same time, pressing the spacebar key while not focused on a text element will no longer result in the page scrolling.
Under the hood, the scroll is still taking place. It's just being reset at a rate fast enough to where the user doesn't notice.
If you increase this value to 100 or 1000, it will give you a better idea of what is going on under the hood. You'll actually see the page scroll and then get set back to the previous scroll position.
This was only tested in Chrome and Firefox 13! So you may have to adjust the setTimeout duration -- currently 0 -- to a different value in browsers like Internet Explorer. Be prepared to gracefully degrade -- by supporting this feature only in modern browsers -- if necessary.
UPDATE:
For reference, below is the method to use to make this compatible in the major browsers. It has been tested in Chrome, Firefox, IE8, IE9, and Safari.
While it does work in IE8/IE9, it isn't very smooth.
// put the eventhandler in a named function so it can be easily assigned
// to other events.
function noScrollEvent(e) {
e = e || window.event;
if(e.keyCode == 32) {
setTimeout(
(function(scrollval) {
return function() {
$(document).scrollTop(scrollval);
};
})( $(document).scrollTop() ), 0);
}
}
// Chrome and Firefox must use onkeydown
window.onkeydown = noScrollEvent;
// Internet Explorer 8 and 9 and Safari must use onkeypress
window.document.onkeypress = noScrollEvent;
If another element is bound to the keydown event it will not be effected by this code
See my fiddle and try adding and remove the textarea listening to the keydown event
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
document.getElementsByTagName("textarea")[0].onkeydown = function(e) {
alert("hi");
}
http://jsfiddle.net/HnD4Y/
The answer above with the setTimeout did not work for me at all on Chome with a delay of 0. With a delay bumped above 50ms, it began to work, but that caused a noticeable page jump. I believe that setTimeout was scrolling the page up too early, then Chrome moved it down later.
Below is my solution that is working well. It returns false on the keydown event to prevent the browser from doing a page-down. Then you make sure event you set up on your button etc. to use the keyup event instead.
$(mySelector).keyup(eventHandlerFunction);
[dom element].onkeydown = function(event) {
if (event.keyCode == 32) {return false;}
};
Note: input fields will not reflect spacebar key events if they or their parent are covered by this onkeydown handler

javascript: capturing function (f1-12) keys [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser
I am working to replace an old vb6 app with a web app. in the old app the save button was linked to f8 and the users of this application want that to stay the same. How can i capture the f8 button so that it is linked to my save button? Thanks
YOu should be able to bind to the 'keyup' event and look at the keyCode. Here is a list of the keycodes you will need.
http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/javascript-char-codes-key-codes.aspx
DOM_VK_F8 = 119, so you should check to see that the keypress event listener's event object's keyCode property is equal to 119.
addEventListener('keypress', function(e) {
if (e.keyCode == 119)
; // do stuff here
}, false);

Categories