1

I want to try this example, but it is doesn't work. Why ?

<div id="test"></div>
<script>
    $('#test').focus();
    alert($("*:focus").attr("id"))
</script> 
Bdfy
  • 23,141
  • 55
  • 131
  • 179

5 Answers5

8

Note, as others have mentioned, not all elements can be focussed by default. You must add the tabindex attribute to them to make those elements focussable:

<div id="test" tabindex="0"></div>
<script>
    $('#test').focus();
    alert($("*:focus").attr("id"))
</script> 

When the tabindex attribute is applied, your original code works. See this working example.


In plain JavaScript, document.activeElement should return the focussed element, if there is one. It can also return an element that is active, but not focussed. The best way to handle it is to check if the element is focussed:

function getFocussedElement() {
    var el;
    if ((el = document.activeElement) && el != document.body)
        return el;
    else
        return null;
}

It's worth mentioning that this approach should be much faster than querying with selectors. Be aware that activeElement isn't part of any standard, but it is supported by all major browsers.

Andy E
  • 338,112
  • 86
  • 474
  • 445
0

Depending on the browser, div's can't accept focus. Change it to an input, and you're good to go.

<input  id="test"></input >
<script>
    $('#test').focus();
    alert($("*:focus").attr("id"))
</script> 

According to this answer, it all depends on the browser:

The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.

Community
  • 1
  • 1
Doozer Blake
  • 7,677
  • 2
  • 29
  • 40
0

as @lonesomeday said, you can't focus on a div

here's an example with an input element instead http://jsfiddle.net/xsp83/

Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
0

Will this suffice?

$("input").focus(function(){
  var f = $(this).attr("id");
  console.log(f);
});
Nix
  • 5,746
  • 4
  • 30
  • 51
  • If you have a new question, please ask it by clicking the [Ask Question](http://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. – Samuel Rossille Nov 16 '12 at 03:58
  • @SamuelRossille Huh? This is a one year old answer, not a question. ;) – Nix Nov 16 '12 at 06:59
0

I don't think the div element will be able to gain the focus, from the focus() docs -

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.)

cHao
  • 84,970
  • 20
  • 145
  • 172
ipr101
  • 24,096
  • 8
  • 59
  • 61