I have a scenario where I have to prepare a JS method where Tab key should fire . i.e. When the Function is executed Tab button click should fire. preferably using Key code.
You can dispatch keyboard events, but the results might be less than overwhelming.
As shown below, you can dispatch an event with appropriate properties, but in some browsers the values are empty and the browser virtually ignores it. You can tab to the button and press "Enter" to click it. It dispatches a tab, but focus doesn't move and the associated event doesn't report the values set in the constructor.
Typing into the input shows the type of result you should get. Try it in lots of browsers.
function showEventProperties(evt) {
document.getElementById('details').innerHTML = ['type','key','code','keyIdentifier','charCode','which','keyCode'].map(function(key) {
return key + ': ' + evt[key];
}).join('<br>');
}
function sendTab(node) {
var evt = new KeyboardEvent('keypress', {
'view': window,
'bubbles': true,
'key': 'Tab',
'charCode': 9,
'keyCode': 9,
'which': 9
});
node.dispatchEvent(evt);
}
window.onload = function() {
document.addEventListener('keypress', showEventProperties, false);
}
<input onkeypress="showEventProperties(event)">
<br>
<button onclick="sendTab(this)">Do tab</button><button>Next button</button>
<p id="details"></p>
You can also try the older initKeyEvent.
Related
In JavaScript, is it possible to distinguish between beforeunload events that were triggered by the user closing a browser tab vs clicking a mailto link?
Basically, I would like to do this:
window.addEventListener("beforeunload", function (e) {
if(browserTabClosed) {
// Do one thing
}
else if (mailtoLinkClicked) {
// Do a different thing
}
}
Found a solution by looking at the event (e below) that gets passed in:
window.addEventListener("beforeunload", function (e) {
// We can use `e.target.activeElement.nodeName`
// to check what triggered the passed-in event.
// - If triggered by closing a browser tab: The value is "BODY"
// - If triggered by clicking a link: The value is "A"
const isLinkClicked = (e.target.activeElement.nodeName === "A");
// If triggered by clicking a link
if (isLinkClicked) {
// Do one thing
}
// If triggered by closing the browser tab
else {
// Do a different thing
}
}
The beforeunload method has an unstable behaviour between browsers, the reason is that browser implementations try to avoid popups and other malicious code runned inside this handler.
There is actually no general (cross-browser) way to detect what triggered the beforeunload event.
Said that, in your case you could just detect a click on the window to discriminate between the two required behaviours:
window.__exit_with_link = false;
window.addEventListener('click', function (e) {
// user clicked a link
var isLink = e.target.tagName.toLowerCase() === 'a';
// check if the link has this page as target:
// if is targeting a popup/iframe/blank page
// the beforeunload on this page
// would not be triggered anyway
var isSelf = !a.target.target || a.target.target.toLowerCase() === '_self';
if (isLink && isSelf) {
window.__exit_with_link = true;
// ensure reset after a little time
setTimeout(function(){ window.__exit_with_link = false; }, 50);
}
else { window.__exit_with_link = false; }
});
window.addEventListener('beforeunload', function (e) {
if (window.__exit_with_link) {
// the user exited the page by clicking a link
}
else {
// the user exited the page for any other reason
}
}
Obviously it is not the proper way, but still working.
At the same way, you could add other handlers to check other reasons the user left the page (eg. keyboard CTRL-R for refresh, etc.)
Using pure JS I'd like to intercept the arrow key and dispatch the enter key in its place to submit a form. The enter key is being dispatched it's just not behaving like the enter key does when you physically push it on the keyboard, I know I could just use click() to do the same thing its just really bothering me that I cant get the enter key to work how I expect..
See fiddle
var input = document.getElementById('name');
input.addEventListener('keydown', e => handleArrowNavigation(e));
function handleArrowNavigation(event) {
if (event.key === "ArrowRight") {
//send enter to expand
triggerEnterKey(event.target.id);
}
}
function triggerEnterKey(elementId) {
var element = document.getElementById(elementId);
if (element) {
const keyEvent = new KeyboardEvent("keydown", {
key: "Enter",
//code: "Enter",
//keyCode: 13,
//charCode: 13,
//type: "keydown",
//isTrusted: true,
//defaultPrevented: true,
//currentTarget: element,
//view: window,
//bubbles: true
});
var dispatched = element.dispatchEvent(keyEvent);
console.log("enter key triggered on element: " + element.id);
console.log("event dispatched: ", dispatched);
//element.click();//click works
}
}
<form action="javascript: alert('form submitted.')">
<p>
If you hit enter while focus is on the input you will get an alert as expected. If you click the right arrow key I'd like it to trigger the enter key and do what enter does. (right arrow key should trigger form submission alert)
</p>
<input type="text" id="name" />
<input type="submit" id="submit" />
</form>
Actually just figured this out... You can't.
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Note: Manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.
I want to automatically swipe tik-tok videos, so I tried this in Chrome console, but it doesn't work.
var event = new KeyboardEvent('keydown');
document.dispatchEvent(event);
I think Tiktok is most likely preventing untrusted keyboard events from triggering the scroll. If you run this code
window.addEventListener('keydown', (e) => {
console.log(e)
})
window.dispatchEvent(
new KeyboardEvent('keydown',{
//keycode and code for down arrow
keyCode:40,
code:'ArrowDown'
})
)
You'll get a KeyboardEvent object logged that looks something like this
KeyboardEvent {isTrusted: false, key: "", code: "ArrowDown", location: 0, ctrlKey: false, …}
Im pretty sure that Tiktok's keypress/keydown listener ignores synthetic keypresses (prolly by checking event.isTrusted) and thus automatically scrolling by simulating the down arrow press is probably out of question. However, you could target the next button on page and click it.
// this is the class name for the up and down button
let buttonSelector = '.up-and-down';
let buttons = document.querySelectorAll(buttonSelector)
let prev, next = null;
// if theres one button, then its the next
if(buttons.length == 1)
next = buttons[0]
//if not then the first button is prev, and the last next
else
[prev, next] = buttons
//now click
next && next.click();
How can I call a javascript function on CTRL + Space?
function getdata() {
console.log("hello");
}
When I hit the getdata() function on CTRL + Space and gives me autosuggestion.
If user type something on my textbox like sta
User types CTRL + Space
It should give me a auto suggestions like stack, stackover, stackoverflow
In order to accept the keyboard input from CTRL + SPACE you'll need to register an event handler (http://www.quirksmode.org/js/events_tradmod.html) and then listen out for input from the user. This will read from an array of keystroke events and check whether they're true, then fire event when keys have been pressed, when they get released the events are false.
var map = {17: false, 32: false};
$(document).keydown(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[17] && map[32]) {
// FIRE EVENT
}
}
}).keyup(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = false;
}
});
if you go to this link: cambiaresearch.com/articles/15/javascript-char-codes-key-codes, you'll find that the keycodes are all listed here. 17 and 32 is CTRL + SPACE.
check out this guide on auto_complete with JQuery. This code will be executed where the event is fired.
https://github.com/mliebelt/jquery-autocomplete-inner
Look at this answer. - https://stackoverflow.com/a/16006607/2277126
Here you have list of key codes key codes
Good luck!
Here's how I got JQuery autocomplete to show its dropdown list when the user presses Ctrl + space:
$( "#" + myElementId )
.on( "keydown", function( event ) {
// Ctrl+space opens the autocomplete dropdown
if (event.keyCode === $.ui.keyCode.SPACE && event.ctrlKey ) {
$(this).autocomplete("search");
}
});
What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?
I don't want to actually put text in the input box, I just want to trigger all the event handlers that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.
So how would one accomplish this?
You can trigger any of the events with a direct call to them, like this:
$(function() {
$('item').keydown();
$('item').keypress();
$('item').keyup();
$('item').blur();
});
Does that do what you're trying to do?
You should probably also trigger .focus() and potentially .change()
If you want to trigger the key-events with specific keys, you can do so like this:
$(function() {
var e = $.Event('keypress');
e.which = 65; // Character 'A'
$('item').trigger(e);
});
There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.
You could dispatching events like
el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
To trigger an enter keypress, I had to modify #ebynum response, specifically, using the keyCode property.
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
Here's a vanilla js example to trigger any event:
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question
const input = document.getElementsByTagName("input")[0];
// focus on the input element
input.focus();
// add event listeners to the input element
input.addEventListener('keypress', (event) => {
console.log("You have pressed key: ", event.key);
});
input.addEventListener('keydown', (event) => {
console.log(`key: ${event.key} has been pressed down`);
});
input.addEventListener('keyup', (event) => {
console.log(`key: ${event.key} has been released`);
});
// dispatch keyboard events
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
<input type="text" placeholder="foo" />
MDN dispatchEvent
MDN KeyboardEvent
You're now able to do:
var e = $.Event("keydown", {keyCode: 64});
First of all, I need to say that sample from Sionnach733 worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.
function triggerEvent(el, type, keyCode) {
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.keyCode = keyCode;
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.keyCode = keyCode;
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press
For typescript cast to KeyboardEventInit and provide the correct keyCode integer
const event = new KeyboardEvent("keydown", {
keyCode: 38,
} as KeyboardEventInit);
I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout().
e.g.
setTimeout(function() { $("#txtName").keypress() } , 1000);
Any use of $("#txtName").keypress() was ignored, although placed at the end of the .ready() function. No particular DOM supplement was being created asynchronously anyway.