0

There are lots of methods allowing one element getting click and another element getting focused but using them on making the element itself getting focused seems to be a waste of resource.

I tried

<div onclick="this.focus()"></div>

and

<div onclick="this:focus"></div>

and it didn't seem to work.

No jquery please, and don't capture all the clicks. It's an overkill for resource.

James Wayne
  • 1,894
  • 14
  • 14

2 Answers2

3

You have to set the tabindex of the div to 0 in order to allow it to be focused by the user:

<style>
div:focus {
   background-color:yellow;
}
</style>

<div tabindex="0" onclick="this.focus();">CLICK HERE to Focus</div>
SergiP
  • 106
  • 5
0

From Mozilla:

If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.

Also note that not all HTML elements can receive focus. (See this SO page.)

Ted's idea of scrolling to it using an anchor is a good one.

Community
  • 1
  • 1
freginold
  • 3,946
  • 3
  • 13
  • 28