Reputation: 1770
I am trying to give focus to the following button in my Angular 2 application:
<button (click)="confirmOk(modalId)" class="btn btn-default ok" id="ok-button" tabindex="0">
<img src="/assets/shared/images/icon-ok.png" />
{{okText}}
</button>
On the page, I open the developer console (F12) and type the following:
var e = document.getElementById("ok-button");
At this point, it returns the element I'm expecting, so I know JavaScript is finding the button. So then I go back into the console and type:
e.focus();
... and the button doesn't get focus. I know it's not getting focus because I have a CSS class for this button's :focus state that should put a big red border around the button if it receives focus. And I can indeed see that red button when I manually click on the button to give it focus.
Following the suggestions in the comments, I also tried adding this code to the event which triggers the button to appear on the page:
showButton(); // the button is triggered to appear here
setTimeout(function() {
let e = document.getElementById('ok-button');
if (e) {
e.focus(); // breakpoint here does indeed get triggered
}
}, 2000)
Unfortunately, that also didn't work.
Update: this may be helpful. When I click Refresh on the browser, the target button momentarily receives focus before the page actually refreshes. So my guess is it's something to do with the timing on the page, or maybe Angular's repainting of the page?
Upvotes: 2
Views: 2577
Reputation: 1770
The problem was simply that the console was open while I was trying to get focus. Even if I didn't type in the console, it was constantly somehow stealing focus. Once I closed the console, and I tried to get focus from code rather from the browser, the focus was successfully applied.
Upvotes: 2