Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari: focus event doesn't work on button element

The focus event works fine on all browsers but Safari when it has been clicked.

And it works fine on div[tabindex] element, but don't work on button or input:button element.

It also can get the focus event when I use $('.btn').focus().

Why does the focus event haven't triggered on click ?

Here is my code:

$(".btn").focus(function (e) {
	$(".result").append("<p>Event:"+e.type+", target:"+e.target+"</p>");
})
.result{min-height:200px;border:1px solid #000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn">button 1</button>
<input type="button" class="btn" value="button 2"/>
<div class="btn" tabindex="0">div element</div>
<h1>
Result:
</h1>
<div class="result">

</div>
like image 661
Woody Avatar asked Mar 13 '17 08:03

Woody


People also ask

Which events is triggered when an element of form loses focus?

Events focus/blur The focus event is called on focusing, and blur – when the element loses the focus.

What is Focus event in Javascript?

The focus event fires when an element has received focus. The main difference between this event and focusin is that focusin bubbles while focus does not. The opposite of focus is blur . This event is not cancelable and does not bubble.

Does focus work on Safari?

Finally :focus-visible has been enabled by default in WebKit and shipped in Safari 15.4, which completes the work on the first Open Prioritization experiment.


2 Answers

Documentation tells is not supported: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus

enter image description here

like image 160
Chris Tapay Avatar answered Sep 21 '22 00:09

Chris Tapay


Why does the focus event haven't triggered on click ?

We found through research that Safari and FireFox on Macs do not set focus on buttons when you click on them.

The way we fixed that was to add a click listener to our buttons and call focus() on the button that was clicked.

In Angular it looked like this:

<button (click)="myClickFunction(); $event.target.focus();>My Button</button>
like image 45
Brian Bjork Avatar answered Sep 20 '22 00:09

Brian Bjork