最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Give <a> element autofocus - Stack Overflow

programmeradmin4浏览0评论

With the following code I try to give an a element autofocus when the page is loaded.

<a href="/{{setting}}" id="next" class="button big active">Next vocabulary</a>
<script>
    document.getElementbyId("next").focus();
</script>

Whilst this works fine with input fields it doesn't work with that a element. Can anybody explain me while?

Regards

With the following code I try to give an a element autofocus when the page is loaded.

<a href="/{{setting}}" id="next" class="button big active">Next vocabulary</a>
<script>
    document.getElementbyId("next").focus();
</script>

Whilst this works fine with input fields it doesn't work with that a element. Can anybody explain me while?

Regards

Share Improve this question asked Mar 5, 2012 at 11:42 orschiroorschiro 21.9k22 gold badges70 silver badges96 bronze badges 5
  • 1 ...because there's nothing to type in an a element? – user554546 Commented Mar 5, 2012 at 11:44
  • 1 Why would you focus an a element ? I don't think that there an real .focus() for a. Maybe highlight it with css ? – mas-designs Commented Mar 5, 2012 at 11:45
  • 1 Because it is an interactive control. Pressing tab will go to the next one in sequence. Pressing enter will follow the link. – Quentin Commented Mar 5, 2012 at 11:47
  • 2 Which browser you are testing on? Works on my chrome and ie. I assume getElementbyId is a typo not done in your code, if I'm wrong change that to getElementById. – Prusse Commented Mar 5, 2012 at 11:52
  • 1 Just to make it clearer: Autofocusing a link makes a lot of sense for people using assistive software. For example, when a modal window popups up with a list of links, it makes sense to focus the first link so that the user can easily navigate through the list. – jlh Commented Nov 25, 2020 at 16:35
Add a ment  | 

2 Answers 2

Reset to default 6

The problem is that you typed getElementById wrong, it should be an uppercase 'B'.

<a href="/{{setting}}" id="next" class="button big active">Next vocabulary</a>
<script>
    document.getElementById("next").focus();
</script>

This should now work!

Currently, autofocus can be applied to more than just input elements (such as link).
So that's it.

<a href="/{{setting}}" id="next" autofocus>Next vocabulary</a>

The autofocus attribute applies to all elements, not just form controls.
autofocus - HTML: HyperText Markup Language | MDN

Since

  • Google Chrome 79 (Released 2019-12-10)
  • Firefox 110 (Released 2023-02-14)
  • Safari 15.4 (Released 2022-03-14)

Spec

Make 'autofocus' a global attribute by tkent-google · Pull Request #4830 · whatwg/html

发布评论

评论列表(0)

  1. 暂无评论