Reputation: 24621
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>
Upvotes: 1
Views: 18616
Reputation: 344537
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.
Upvotes: 8
Reputation: 24236
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.)
Upvotes: 0
Reputation: 5998
Will this suffice?
$("input").focus(function(){
var f = $(this).attr("id");
console.log(f);
});
Upvotes: 0
Reputation: 10305
as @lonesomeday said, you can't focus on a div
here's an example with an input element instead http://jsfiddle.net/xsp83/
Upvotes: 0
Reputation: 7797
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.
Upvotes: 0