Focus adress bar on page load [duplicate] - javascript

Desired behavior : When a Tabkey press happens on a particular dom element in a webPage I want my cursor focus to go to address bar.
(I want it via Javascript. Using any browser extension is not what is desired here)
When you press Control + L shortcut in a webpage, it takes your focus to address bar.
But when I try to trigger this via javascript it does'not work.
<div id="1" tabindex="1"></div>
<div id="2" tabindex="1"></div>
<div id="3" tabindex="1"></div>
<script>
var some = $('#1');
some.on('keydown', function (e) {
if (e.keyCode == 9 /* TabKey */) {
var e = jQuery.Event("keydown");
e.keyCode = 76 /* LKey */;
e.ctrlKey = true;
$('body').trigger(e);
}
});
</script>

Each browser (and operating system) handles this differently and it is not currently possible to highlight the address bar using javascript. Even if it was, keep in mind that people can map these commands differently (if they're not different already). For example, on a mac the command to access the address bar is Command + L, not Ctrl + L.

According to Trusted events in the UI Events specification
Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the createEvent() method, modified using the initEvent() method, or dispatched via the dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.
So triggering the CTRL+L event will have no effect on your browser which will need a trusted event for opening the address bar.
And yes, as already said by some people, removing default browser behaviour does not help accessibility.
On a purely technical point of view, jQuery UI gives you a very quick way for answering the use case in your comments. This will move to the last focusable element on "keydown", and then when you relapse the tab key, will go to the default element after your page (address bar, depending on your browser)
$("#MyLastElement").on('keydown', function (e) {
if((e.keyCode==9)&&(!e.shiftKey)) {
$(":tabbable").last().focus();
}
});

Related

React how to trigger a specific scroll event(arrowUp or arrowDown inside a div) on a key press

I developed chat web application.
I wish to fire scroll event on a specific div(chatPage) whenever (for example)"w" or "s" keys is pressed,
exactly the same way if the chatPage div had the focus on, and ArrowUp or ArrowDown keys was pressed.
Notice: I wish to mimic the default scroll event fired on the browser when "ArrowUp" or "ArrowDown" keys is pressed when a div element have the focus and not accomplish it by other method such as calling current.scrollBy on the reference of the div.
(not like this) :
this.state.chatPageRef.current.scrollBy(0, -20); //"w" key has preesed
this.state.chatPageRef.current.scrollBy(0, 20); //"s" key has preesed
This works ok, but not smoothly as the default scroll of the browser when the arrows keys is being pressed.
Also, I do not wish to use any external React API that knows how to trigger events but using only React standard libraries.
instead, i wish to use more something like this:
var scrollEvent = new Event("scroll", {
bubbles: true,
cancelable: true
view: window
// probobaly here some proparties need to be added
});
document.getElementById("chatPage").dispatchEvent(scrollEvent)
Which does fire a scroll event, but not the same event as explained above so its do nothing.
I do not know how to define the Event() constructor to mimic the
exact event fired by the browser whenever "ArrowUp" or "ArrowDown" keys is pressed when a specific div element have the focus on.
So my question is, how can I find out how to exactly define my scroll Event constructor to mimic specific default browser event(such as scroll a div via arrows on keyboard)?
(answers with instructions how to find out the properties of this specific event via console.log() would also be blessed)
thanks...!
The security model in the browser, blocks direct access to a number of events like this. The solution will be to manually animate the scrolling using requestAnimationFrame to feed smaller increments to the code in your question.

Block or detect key events coming from inside autocomplete list

I have a form with multiple stacked <input type="text"> boxes, and I check for an "Enter" press on the form's keydown event, moving to the next input down if this happens, and returning false to prevent form submission. (Yes, that's the oldschool way... but I want to support legacy browsers).
form.onkeydown = checkEnter;
and
function checkEnter(e)
{
e = e||window.event;
var el, tag, typ, k = e.keyCode||e.which;
if ((k===13)&&(el = e.target||e.srcElement)&&(((tag = el.tagName)==="SELECT")||((tag==="INPUT")&&((typ = el.type)!=="submit")&&(typ!=="reset")&&(typ!=="button"))))
{
// focus next form element
// ...
return false;
}
}
The problem is that if I press down-arrow in an input and the autocomplete list opens, I can select a value from that list using the mouse as normal, but if I choose a value using the arrow keys instead and then press "Enter" to select that value, my event prevents this from happening in Firefox 61 and Edge 42 (but it does work as expected in Chrome 67). This makes autocomplete unusable without a mouse.
My question is: Can I block keydown events from triggering when the focus is inside the autocomplete history list, rather than inside the element itself? Or alternatively, can my event somehow detect that the autocomplete list is showing? I'd like "Enter" pressed while in the autocomplete list to perform its default behaviour, i.e. selecting the autocomplete entry.
Note that Chrome is possibly avoiding the issue because the value in the <input> changes as you navigate the autocomplete list.
Note that changing to using the keypress event (instead of keydown) makes no difference (at least in FF 61).
Turns out that what was interfering with autocomplete was not the
return false;
Rather, it was the part where I set focus to the next form element. This solved the specific problem I was having (note the change to keydown instead of keypress, it's necessary):
form.onkeypress = checkEnter;
and
function checkEnter(e)
{
e = e||window.event;
var el, tag, typ, nextEl, k = e.keyCode||e.which;
if ((k===13)&&(el = e.target||e.srcElement)&&(((tag = el.tagName)==="SELECT")||((tag==="INPUT")&&((typ = el.type)!=="submit")&&(typ!=="reset")&&(typ!=="button"))))
{
// nextEl = form element to switch focus to next
// ...
if (nextEl) setTimeout(function(){nextEl.focus()},0);
return false;
}
}
i.e. defer the focus change until after the keypress event has completed, using setTimeout().
So I answered my specific problem, of fixing autocomplete behavior in this case. But I still don't know the answer to the general question as I posed it, i.e.:
Can I block keydown events from triggering when the focus is inside
the autocomplete history list, rather than inside the element itself?
Or alternatively, can my event somehow detect that the autocomplete
list is showing?
For example, I have another page where I want an "Enter"-press in an <input> to perform a specific action, only not if it was pressed to select an autocomplete entry.
...So if anyone has a solution to the more general problem, please post it!

Change accesskey modifier keys in Firefox

I'm working on a website where each page has buttons, like "submit" and "cancel". Each of these buttons has an accesskey attribute. The submit button's accesskey attribute is set to S, and the cancel button's accesskey attribute is set to C.
Access keys are activated using different modifiers in different browsers. Internet Explorer, Safari, and Google Chrome use just the alt, while Firefox uses both the alt and the shift keys. As well, Firefox uses alt + s to open the history menu.
Answers to this question should not suggest changing settings in the browser's configuration as that would not be feasible on a production site.
How I change the modifier keys that Firefox uses for accesskey's to just alt, and prevent the history menu from opening?
I am working in Ubuntu 16.04.
You cannot—as far as I can tell—change the key combination required to activate an accesskey, but what you're trying to achieve does not require use of the accesskey attribute. You can listen for the keydown event directly.
Add a keydown event listener to the document. In the handler function check to see if the alt and s keys are pressed. If they are—and no other modifier keys are pressed—prevent the default action of the event, then trigger a click event on the submit button.Triggering the click event on the submit button will in turn trigger the submit event listener, whereas triggering the submit event on the form directly may not.
const submit = document.querySelector('#submit')
document.addEventListener('keydown', e => {
// If the only modifier key is the alt key, and the s key is pressed
if(!e.metaKey && !e.ctrlKey && !e.shiftKey && e.altKey && e.key === 's') {
e.preventDefault() // Prevent the mozilla history menu from opening
submit.click() // Trigger the form submission
}
})
<form action=""><button type="submit" id="submit"><u>S</u>ubmit</button></form>
Notes:
1. Though this works in the current stable version of Firefox, I have not tested other versions
2. This example uses language features introduced in the 2015 version of The ECMAScript Language Specification. These features are not required to achieve the desired effect, but make the code easier to read. If you need to support older browsers, you can use var instead of const, and a standard function instead of the fat arrow function.
3. Unfortunately—due to sandboxing—the Stack Overflow snippet feature does not work for this example, see this example on JSBin instead
If you want deep knowledge about it then try this article has more info: http://kb.mozillazine.org/Ui.key.contentAccess
If you find that you can't get used to the "in-tab" preferences dialog, there is a preference to return to the old style dialog:
In a new tab, type or paste about:config in the address bar and
press Enter. Click the button promising to be careful.
In the search box above the list, type or paste pref and pause while
the list is filtered
Double-click the browser.preferences.inContent preference to switch
it from true to false
Note: I don't know whether that will be in Firefox forever or is a transitional feature.

Triggering default behavior on enter key press simulation

So (just to start with "so") I want to create a greasemonkey script for a qwebirc platform. I need to send replies automatically based on some events that happen. For those who don't know, once logged in the qwebirc, there is an input text field at the bottom of the screen where you can write your reply and then, by pressing enter, the reply is sent to the server. The input field is contained in a form element, but the form has no submit button.
I can populate the input field (no problem) by writing to its "value" attribute, but I found no way to "submit" the reply to the server. I tried calling the .submit() method on the container form element, but that simply reloads the page (so it's sending to itself - and that makes sense, 'cause there's no "action" attribute on the form element). It seems to me that the only explanation is that once the enter key is pressed in the input field there's a method that's called somewhere on the qwebirc.js.
I can't find the code responsible for this action (though I worked that in Chrome, I set an Event Listener Breakpoint on the Keyboard - Input, and that stopped me when I pressed the enter key and pointed me to the beginning of some function) because the script is minified and there's no way for me to know what those "m", "n", "p", "t" etc mean. If I had the uncompressed version, I could scan it and, maybe, find it out. I also tried downloading the qwebirc project, but there are loads of files there - whereas on the server I'm trying to write the greasemonkey script there's a single script.
The main idea here is that I guess the enter key press simulation should trigger the sending function - wherever and whichever that may be.
In order to do this I found on stackoverflow some questions with the same subject - the simulation of enter key press. I tried that code:
function simulate() {
var evt = document.createEvent('KeyboardEvent'),
input = document.querySelector('.keyboard-input');
evt.initKeyboardEvent(
'keydown',
true,
true,
window,
false,
false,
false,
false,
13,
0
);
input.dispatchEvent(evt);
}
The event is created (I can see it in my DOM panel in FireBug), but no action whatsoever is taken. I mean why doesn't the .dispatchEvent() behave just like a real enter key press ?
Thanks in advance.
For the purposes of this answer, I'm going to assume that the message input pseudo-form is like others - i.e. the message can be sent by either pressing Enter or clicking a Send button.
You've tried the former; it didn't work. It's possible that the page is waiting for the Send button to be clicked (which may be triggered by an Enter keypress (though no, I don't know why your event isn't working - I'm unfamiliar with event intricacies)). Instead, then, try that.
Also, take note: IE uses fireEvent not dispatchEvent - so if you're in IE, this may be the problem.
To fire a click on the Send button:
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
e.target = "button#send";
if(document.fireEvent) {
document.fireEvent(e);
}
else {
document.dispatchEvent(e);
}
Change the string assigned to e.target to the CSS selector that uniquely identifies the Send button.

Make Keyboard keys run JavaScript if the mouse isn't in a Textarea/textbox

Like if they press A regardless of the caps for it to pull up Apps, Pressing D pulls up Dashboard. This should only work if their mouse is not in a area where they can type. How would i do this?
Here is the pseudo code I would follow:
onKeyPress {
if (body.hasFocus && !input.hasFocus ) {
coolStuff();
}
}
Basically, you have an event listener waiting for your particular key(s) to be pressed. You only execute the coolFunc(), however, if they have focus on your webpage (i.e. not the address bar) and they are not inside a input element.
I would also recommend using jQuery; it will make your code a lot cleaner and easier to write.
Let me know if you need an actual JS example, not pseudo-code.

Categories

Resources