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.
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.
<!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>
#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;
}
$(document).on('ready', function() {
$('#container').on('focus', function() {
alert('Focus handler called!');
});
});
Leave a comment