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 theinitEvent()
method, or dispatched via thedispatchEvent()
method. TheisTrusted
attribute of trusted events has a value oftrue
, while untrusted events have aisTrusted
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With