Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take my web page focus to browser address bar using javascript / jquery

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>
like image 595
Rohit Kumar Avatar asked Dec 11 '22 10:12

Rohit Kumar


2 Answers

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.

like image 156
Skerrvy Avatar answered Dec 14 '22 22:12

Skerrvy


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();
  }
});
like image 34
Adam Avatar answered Dec 15 '22 00:12

Adam