Can Javascript press the Enter key for me? - javascript

There's a site that I want to continue to hit enter on while I'm away. Is it possible to do something like
setInterval(function(){
//have javascript press the button with a certain id
},100);
I was thinking of just putting that in the smart search bar so it would run the code.

Well pressing enter is triggering an event. You would have to figure out which event listener they are listening to. I'll use keyup in the following example:
Assume el is the variable for the element you want enter to be pressed on. I'm not sure how you going to get that element but I'm sure you know.
var evt = new CustomEvent('keyup');
evt.which = 13;
evt.keyCode = 13;
el.dispatchEvent(evt); //This would trigger the event listener.
There's no way to actually simulate a hardware action. It just triggers the event listener.
For example calling el.click() is only calling the callback of the event listener, not actually pressing the key.
So you know how when you add an event listener to an element the first argument is the event object.
el.addEventListener('keyup', function(event) {
//Do Something
});
Above event is equal to evt when calling dispatchEvent on el
If the programmer used:
el.onkeyup = function(event) {
//do whatever.
}
It's surprisingly easy.
Just call el.onkeyup(evt);
Because onkeyup is a function.
Why did I use CustomEvent instead of KeyboardEvent because new KeyboardEvent('keyup') return's an object with the properties which and keyCode that can't be rewritten without the use of Object.defineProperty or Object.defineProperties

Related

Not exiting first keypress event when parent function gets fired

Problem
I have a .keypress() event inside of a .click() event. The first time the user clicks on the element, everything works fine, but subsequent clicks trigger the .keypress() event again without "closing" the first one. I've tried adding event.cancelBubble = true; and an empty return statement to break out of the function, but it hasn't worked because predictably, the rest of the code in that execution doesn't get executed but the event is still active and a key press could still trigger it. Is there a way to close the .keypress() event when foo gets clicked?
Code
$(foo).click(function(){
//Do stuff
$(foo).keypress(function(event) {
//Do stuff
});
});
do you mean keypress called more than once?
in your code, every time you click foo, a new anonymous function will be added to keypress event.
unbind the previous keypress event handler before binding new handler
$(foo).click(function(){
//Do stuff
$(foo).off('keypress').on('keypress', function(event) {
//Do stuff
});
});
I'm not entirely sure what you're asking but I think you want to turn off the keypress after the first click. This should toggle it though you may want to make the pressed var global; maybe.
$(foo).click(function(){
//Do stuff
var pressed = false;
$(foo).keypress(function(event) {
if(!pressed){
//Do stuff
pressed = true;
} else {
event.off();
pressed = false;
}
});
});
The key here is event.off() which will remove the listener.

How to change input/textarea value with custom keyboard event and keyCode?

I would like to populate a textarea by triggering keyboard events, such as keydown (I'm doing this for a test case).
I have added a snippet (below) to show the code I'm using to create and trigger the event. The event fires, but the textarea never receives the value of keyCode which is the letter A.
What do I need to do to see the letter in the textarea? I'm currently running the snippet in the Chrome console but it should also work in IE9.
var t = document.getElementById('foo');
// Event creation
var event = document.createEvent('HTMLEvents');
event.initEvent('keydown', true, true);
event.keyCode = 65;
event.which = 65;
// Listener for demo purpose
t.addEventListener('keydown', function (e) {
document.getElementById('fired').value = e.type + ' fired';
});
// Event trigger
t.dispatchEvent(event);
<textarea id="foo"></textarea>
<br>
<input id="fired" value="">
The keydown event is fired when a key is pressed down but it's not the responsible for write the data in the DOM elements.
The thing is; If the user writes on the <textarea> first the character is added to elements value and then the keyDownevent is triggered. However in your case you're directly triggering the event so the first step which is adding the character to the value for <textarea> is not happening.
You have two options, do it in the browser way write the value and then dispatch the event
t.value = t.value + String.fromCharCode(e.keyCode);
t.addEventListener('keydown', function (e) {
document.getElementById('fired').value = e.type + ' fired';
});
Or also you can write the value of the <textarea> on the keyDown event:
// Listener for demo purpose
t.addEventListener('keydown', function (e) {
t.value = t.value + String.fromCharCode(e.keyCode);
document.getElementById('fired').value = e.type + ' fired';
});
however if you want to use this second approach for user interaction it's a nonsense because in the case that the users inputs the data, the data will be write it twice (one for the user input and the another one in the event).
Hope this helps,
Javascript sending key codes to a <textarea> element
I had a look around and this seems more relevant than my non-relevant answer before. Sorry about that. I know this is jquery, but the premise is the same.
adding this in the event would work
document.getElementById('foo').innerHTML += String.fromCharCode(e.keyCode);
here it is in pure javascript jsfiddle
Why does not the value change after triggering keydown?
In short: you can't change the value of input/texarea with dispatching KeyboardEvent programmatically.
How actually do chars come into input? On MDN you can find the description of Keyboardevent sequence (assuming that preventDefault is not called):
A keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true.
If the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down.
A keyup event is fired once the key is released. This completes the process.
So, keydown leads to input event by default. But that is true only for trusted events:
Most untrusted events will not trigger default actions, with the exception of the click event... All other untrusted events behave as if the preventDefault() method had been called on that event.
Basically trusted events are those initiated by a user and untrusted events are initiated with a script. In most browsers, each event has an attribute isTrusted indicating if the event is trusted or not.
And how to test KeyboardEvents on inputs then?
Well, first of all, think if you really need a KeyboardEvent handler. Maybe you can do everything in InputEvent handler. That means that you can just set the value of the input in your tests and then trigger InputEvent.
If you still need KeyboardEvent handler than it depends on what is going on in it. E.g. if you call preventDefault in certain conditions then you can check if it was called or not in a test using a spy. Here is an example with sinon as a spy and chai as assertion library.
const myEvent = new KeyboardEvent('keydown', { key: 'a' })
sinon.spy(myEvent, 'preventDefault')
document.getElementById('foo').dispatchEvent(myEvent)
expect(myEvent.preventDefault.calledOnce).to.equal(true)

Simulate keypress with jQuery on form element

I'm trying to simulate a keypress with the below code...
jQuery('input[name=renameCustomForm]').live('keyup', function (e) {
console.log('pressed');
});
jQuery('body').click(function (e) {
console.log(jQuery('input[name=renameCustomForm]'));
var press = jQuery.Event("keypress");
press.which = 13;
jQuery('input[name=renameCustomForm]').trigger(press);
});
I got this code from other posts on SO, but it doesn't work. Anyone know why?
Update
Fixed it... it appears triggering "keypress" doesn't automatically trigger "keyup"
Normally, when a user adds something to an inout field, the following events occur:
keydown (once).
keypress (at least once, additional events uccur while the key is pressed down)
keyup (once)
When a key event is simulated, it's not necessary that all events occur in this order. The event is manually dispatched, so the normal event chain isn't activated.
Hence, if you manually trigger the keypress event, the keyup event won't be fired.
You code will trigger a keypress each time you click anywhere on the page..
For your case it might be better to use the .blur() event of the input box..
jQuery('input[name=renameCustomForm]').live('keyup', function (e) {
console.log('pressed');
}).live('blur', function(){
var self = $(this);
console.log( self );
var press = jQuery.Event("keyup");
press.which = 13;
self.trigger( press );
});

Enter key triggering link

I have a JQuery scroller on a page where each item is a div with an id. each div has a link to the next div in the scroller (all on the same page)
$('a.panel').click(function () {
};
I have a click event to all links with the 'panel' class where I check which links was clicked and then do some ajax processing accordingly:
if($(this).attr('href')=="#item2")
{
//do some processsing
}
and once the processing is done I use the scrollTo JQuery method to scroll to the next div
I need to have it that the user can press the enter key instead of clicking on the link.
Now the problem is:
a. I have several links on the same page that all need to have this behaviour.
b. I need to differentiate which link triggered the click event and do some server-side processing.
Is this possible at all?
I appreciate the quick and helpful responses!!Thanks a million for the help!
Focus + enter will trigger the click event, but only if the anchor has an href attribute (at least in some browsers, like latest Firefox). Works:
$('<a />').attr('href', '#anythingWillDo').on('click', function () {
alert('Has href so can be triggered via keyboard.');
// suppress hash update if desired
return false;
}).text('Works').appendTo('body');
Doesn't work (browser probably thinks there's no action to take):
$('<a />').on('click', function () {
alert('No href so can\'t be triggered via keyboard.');
}).text('Doesn\'t work').appendTo('body');
You can trigger() the click event of whichever element you want when the enter key is pressed. Example:
$(document).keypress(function(e) {
if ((e.keyCode || e.which) == 13) {
// Enter key pressed
$('a').trigger('click');
}
});
$('a').click(function(e) {
e.preventDefault();
// Link clicked
});
Demo: http://jsfiddle.net/eHXwz/1/
You'll just have to figure out which specific element to trigger the click on, but that depends on how/what you are doing. I will say that I don't really recommend this, but I will give you the benefit of the doubt.
A better option, in my opinion, would be to focus() the link that should be clicked instead, and let the user optionally press enter, which will fire the click event anyways.
I would like to focus on the link, but am unfamiliar exactly how to do this, can you explain?
Just use $(element).focus(). But once again, you'll have to be more specific, and have a way to determine which element should receive focus, and when. Of course the user, may take an action that will cause the link to lose focus, like clicking somewhere else. I have no idea what your app does or acts like though, so just do what you think is best, but remember that users already expect a certain kind of behavior from their browsers and will likely not realize they need to press "enter" unless you tell them to.
If you do choose to use the "press enter" method instead of focusing the link, you'll likely want to bind() and unbind() the keypress function too, so it doesn't get called when you don't need it.
http://api.jquery.com/focus/
http://api.jquery.com/bind/
http://api.jquery.com/unbind/
Related:
Submitting a form on 'Enter' with jQuery?
jQuery Event Keypress: Which key was pressed?
Use e.target or this keyword to determine which link triggered the event.
$('a.panel').click(function (e) {
//e.target or this will give you the element which triggered this event.
};
$('a.panel').live('keyup', function (evt) {
var e = evt || event;
var code = e.keyCode || e.which;
if (code === 13) { // 13 is the js key code for Enter
$(e.target).trigger('click');
}
});
This will detect a key up event on any a.panel and if it was the enter key will then trigger the click event for the panel element that was focused.

onkeypress() not working

i am trying to catch the keypress event on the window (html page opened with an app which uses gecko engine)
function onkeypress(){
alert("key pressed !")
}
i expect this function to be called whenever any button is clicked, when the focus is on window. But the function is not been called.
Any idea what is going wrong here?
Thanks ...
You should assign that function to an element:
var elem = document.getElementById('id-here');
elem.onkeypress = function(){
alert("key pressed !");
};
You need to set it as the handler on the window object if that's what you're after, like this:
window.onkeypress = function() {
alert("key pressed !")
};
This will capture all keypress events that bubble up (the default behavior, from wherever in the page it happened, with the exception of <iframe>, videos, flash, etc). You can read more about event bubbling here.

Categories

Resources