How to Focus on a <Div> Using JavaScript Focus() Function

Is it possible to focus on a div using JavaScript focus() function?

window.location.hash = '#tries';

This will scroll to the element in question, essentially "focus"ing it.

Make div element receive focus

Set the tabindex="0" on the div, on the assumption that you want the divs to receive focus, rather than child elements.

Updated the answer to add a JS Fiddle demo, showing a JavaScript means of achieving this:

var divs = document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++){
divs[i].setAttribute('tabindex', '0');
}

JS Fiddle demo.

While composing the demo I found that tabindex="-1" allows the element to receive mouse-clicks to assign focus, but not keyboard events (through the tab button), however (and as implied in the comment, earlier, by Fabricio Matté, a tabindex="0" allows for both). So I've used that in the demo, and updated the original answer to reflect that change.

Behavior of tabindex="0" versus tabindex="-1" documented here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets#Using_tabindex

How to focus div?

You have to set tabindex attribute:

http://jsfiddle.net/QAkGV/

<div id="focusedDiv" tabindex="-1"></div>

Or:

$("#focusedDiv").attr('tabindex',-1).focus(function () {
....
});

For style, you could set outline CSS property too:

$("#focusedDiv").css('outline',0).attr('tabindex',-1).focus(function () {
....
});

JavaScript focus a particular element with div class, not div id declaration

element.scrollIntoView(true) will do what you are needing.

Setting focus to a div after show

Replace this line:

$("#message_display_area").focus();

with this line:

window.location.hash = "message_display_area";

Javascript Focus on DIV Element not working on chrome

If you want to make a non-focusable element focusable, you must add a tabindex attribute to it:

<div id="focusme" tabindex="1"></div>

Also, you can use the ID to reach it with the location hash.
See the answer to your question here:
Is it possible to focus on a <div> using javascript focus() function?

Set keyboard focus to a div

you can make a div focusable if you add a tabindex attribute.

see: http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex

The tabindex value can allow for some interesting behaviour.

  • If given a value of "-1", the element can't be tabbed to but focus can
    be given to the element programmatically (using element.focus()).
  • If given a value of 0, the element can be focused via the keyboard and
    falls into the tabbing flow of the document.
  • Values greater than 0 create a priority level with 1 being the most important.

UPDATE: added a simple demo at http://jsfiddle.net/roberkules/sXj9m/



Related Topics



Leave a reply



Submit