Calling focus() on an Anchor Triggers Click Event in a Scenario
Hi,
I have a div and an anchor on my page. Both can take focus. When a key is pressed on the div, I would like to set the focus back to the anchor. The sample code is shown below. I found that on FF/IE, if I hit enter on the div when the div has focus, the anchor is then focused as expected, but a click event is also triggered on the anchor, so the console output becomes this:
on div1 keydown
on div1 click
on anchor1 click
The same problem does not happen with Chrome:
on div1 keydown
on div1 click
Is there a way I can prevent the click event from being triggered on the anchor?
Thank you!
===
$(document).ready(function() {
$('#anchor1').on('click', function() {
console.log('on anchor1 click');
});
$('#div1').on('keydown click', function(e) {
switch (e.type) {
case 'keydown':
console.log('on div1 keydown');
$('#div1').trigger('click');
$('#anchor1').focus();
break;
case 'click':
console.log('on div1 click');
}
});
});
</script>
</head>
<body style="font:15px arial,sans-serif;">
<a href="#" id="anchor1">anchor1</a>
<div id="div1" tabIndex="0">div1</div>
</body>
</html>