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>
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Note, as others have mentioned, not all elements can be focussed by default. You must add the
tabindexattribute to them to make those elements focussable:When the
tabindexattribute is applied, your original code works. See this working example.In plain JavaScript,
document.activeElementshould 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:It’s worth mentioning that this approach should be much faster than querying with selectors. Be aware that
activeElementisn’t part of any standard, but it is supported by all major browsers.