sdvnksv
sdvnksv

Reputation: 9668

JS dispatch event

I am trying to focus on a link with a given index using js dispatch event:

var link = document.querySelector(".navbar-nav > li:nth-child(" + index + ") > a");
var event = new Event("focus");
link.dispatchEvent(event);

The code above won't work whereas the jQuery version works OK:

$(".navbar-nav > li:nth-child(" + index + ") > a").focus();

I am testing in the latest Chrome. What is wrong with the JS version?

Upvotes: 0

Views: 1122

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

If you want to set the focus, then just call the focus method of the dom element

function setFocus(index) {
  var link = document.querySelector(".navbar-nav > li:nth-child(" + index + ") > a");
  link.focus()
}
<ul class="navbar-nav">
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
</ul>
<button onclick="setFocus(1)">1</button>
<button onclick="setFocus(2)">2</button>
<button onclick="setFocus(3)">3</button>
<button onclick="setFocus(4)">4</button>

Dispatching the event will not set the focus, that will just trigger the attached event handlers.

In jQuery calling the focus() method will trigger the event and will also call the native behavior method if needed that is why that is working

Upvotes: 1

Related Questions