How to receive focus on a div element

If you want to receive focus on a <div>, <li>, or another element like these, you must set the tabindex attribute on that element. Otherwise, the focus handler won't be called. I usually set the tabindex to zero since I don't want the user to <tab> to the element.

Below is some example code to demonstrate this. I wrote a simple HTML page with a <div>, and used jQuery to setup the focus event handler.

You can download the example here.

What does the example look like?

The tabindex is set in the HTML below, and the alert is seen when you click on the <div>. If you remove the tabindex attribute, the focus handler will not be called.

The HTML

<!DOCTYPE html>
<html>
<head>
  <title>How to setup a focus handler for a div</title>
  <script src="jquery-2.2.0.min.js" type="text/javascript"></script>
  <script src="index.js" type="text/javascript"></script>
  <link href="style.css" rel="stylesheet"/>
</head>
<body>
  <div tabindex="0" id="container">Click here to focus on the element</div>
</body>
</html>

The CSS

#container
{
    height: 150px;
    width: 600px;
    background-color: lightblue;
    color: royalblue;
    font-size: 2em;
    font-family: sans-serif;
    text-align: center;
    margin: 0 auto;
    padding: 20px 10px;
}

The JavaScript

$(document).on('ready', function() {
    $('#container').on('focus', function() {
        alert('Focus handler called!');
    });
});

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.