How to Give Keyboard Focus to a Div and Attach Keyboard Event Handlers to It

How can I give keyboard focus to a DIV and attach keyboard event handlers to it?

Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example

<div id="inner" tabindex="0">
this div can now have focus and receive keyboard events
</div>

Information gleaned from http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html

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/

How to bind keyboard events to div elements?

You can add a tabindex in that div to catch keyboard events like this

<div id="div" style="height:50px" class="ui-widget-content" tabindex="0"></div>

Like answered here.

Working Fiddle

Reference

How to grab keyboard events on an element which doesn't accept focus?

A div by default cannot be given focus. However, you can change that by adding a tabindex attribute to the div:

<div tabindex="0" id="example"></div>

You can then give the div focus, and also blur it with the hover event:

$("#example").hover(function() {
this.focus();
}, function() {
this.blur();
}).keydown(function(e) {
alert(e.keyCode);
});

When the div has focus, it will accept keyboard events. You can see an example of this working here.

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.

Focus on div without click in React to enable keyboard navigation on a module

You'll need to fire a focus() event on the <div> you want to have focus after it has rendered.

The easiest way to do this is to use React's built-in lifecycle methods. First, create a ref for the element you want to have focus (in this case, the div listening for keyDown events). Then, you can call focus() on that node in your component's componentDidMount() method:

class ImageGallery extends React.Component {
construtor(){
super();

// Create the ref in the constructor
this.focusRef = React.createRef();
}

/* your other methods here */

componentDidMount(){
// Focus on the rendered div using the DOM focus() method
this.focusRef.focus();
}

render(){
// Set the ref in your render() method
return(<div ref={this.focusRef} onKeyDown={this.handle}></div>);
}
}


Related Topics



Leave a reply



Submit