5

How can I make jquery .focus() to work without setting tabindex of a div

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

<div id="msgdiv" tabindex="100"> </div>

what is the best practise for this

what i want to achieve: After changing the password i want to display the acknowledgment message that the password has been changed and put focus on that div.

maztt
  • 12,278
  • 21
  • 78
  • 153

3 Answers3

6

Simply, you can't do focus on a div without tabindex, see documentation.

Don't really know what you wanna achieve with this code-snippet, but if you wanna trigger a focus event, you should use trigger:

$("#msgdiv").trigger('focus');
4

the div needs a tabindex in order to receive focus, you can set one via the jQuery before the focus() function, without having to manually add it to the HTML though - if that's what you're asking

$("div").attr("tabindex",-1).focus(function() { 
// do something
});
clairesuzy
  • 27,296
  • 8
  • 54
  • 52
2

A div can only receive focus if it has the tabindex attribute.

What do you actually want to achieve here?

Calum
  • 5,308
  • 1
  • 22
  • 27