Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Javascript press the Enter key for me?

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.

like image 244
robberger Avatar asked Apr 18 '15 15:04

robberger


People also ask

How I press Enter button from JavaScript?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

How do I press Enter programmatically?

You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.

How do you press Enter with keys?

Just look at such a keyboard: the Return key says “Return”, and the Enter key says “Enter”. If your keyboard doesn't have a dedicated Enter key, you can type the Enter key by pressing Fn-Return. That's why some Return keys have “Enter” printed in small type above the word “Return”.

How do you check if the Enter key is pressed?

keyCode === 13) { console. log('Enter key pressed') } }); to check if the key with key code 13 is pressed. If it is, then we know the enter key is pressed.


1 Answers

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

like image 173
Edwin Reynoso Avatar answered Nov 04 '22 13:11

Edwin Reynoso