I have an html text node (an li
tag in this case) that I am trying to trigger focus on using jQuery:
$('#branch').focus();
Or even:
$('#branch').trigger('focus');
I have attached an event listener:
$('#branch').on('focus', function() { console.log('focused'); });
But the event listener isn't firing. What do I need to do to fire this event listener?
If I listen for a 'hocus' event, and fire that event instead, the listener does indeed fire:
(I need this to unit test what happens when you focus on the node, I'm building an accessible tree )
As detailed by Shane Tomlinson here :
Text nodes are considered to be inert, and therefore cannot be "focused" according to the w3c
Firing jQuery's .focus()
method on a text node basically just gets swallowed up.
Instead, you have to use vanilla JS (works in Chrome, haven't tested other browsers):
$('#branch').on('focus', function () {
console.log('jquery listened');
});
var branch = document.getElementById('branch');
branch.addEventListener('focus', function() {
console.log('js listened');
});
// $('#branch').focus(); // this doesn't work! Use JS below instead...
var event = new Event('focus');
branch.dispatchEvent(event);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.