最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why blur and focus doesn't work on Safari? - Stack Overflow

programmeradmin2浏览0评论

I have simple button like that:

<button class="emoji-button-container" onblur="APP.hideEmojiContainer()" onclick="APP.toggleEmojiContainer()">

On Chrome both event works perfectly.

On Safari onclick event works without any problem, but onblur event doesn't get triggered. Also element.blur() function doesn't trigger onblur event. I need it to work on Safari just like on Chrome, so what can I do? what's problem here?

I have simple button like that:

<button class="emoji-button-container" onblur="APP.hideEmojiContainer()" onclick="APP.toggleEmojiContainer()">

On Chrome both event works perfectly.

On Safari onclick event works without any problem, but onblur event doesn't get triggered. Also element.blur() function doesn't trigger onblur event. I need it to work on Safari just like on Chrome, so what can I do? what's problem here?

Share Improve this question asked Apr 16, 2020 at 8:31 O. ShekriladzeO. Shekriladze 1,5363 gold badges23 silver badges46 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

On Safari, buttons may not be focused on click (and because they do not focus, they do not trigger blur)

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus

You can focus the button using javascript though

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            function clickFunc(event) {
                console.log(event, 'click');
                event.target.focus();// Add me
            };

            function blurFunc(event) {
                console.log(event, 'blur');
            };
        </script>
    </head>

    <body>
        <button class="emoji-button-container" onblur="blurFunc(event)" onclick="clickFunc(event)"></button>
    </body>
</html>

It seems Safari doesn't focus button element on click. So, according to definition, onblur attribute fires the moment that the element loses focus. Element is not focused => onblur doesn't fire.

One of the solution could be manually apply button.focus() after click.

Another one is to attach click event on document as here

Try the Safari settings that are not enabled by default: • Go to Safari > Preferences.

  • Click on the Advanced tab.
  • Check the box at the bottom that says "Press Tab to highlight each item on a webpage."
发布评论

评论列表(0)

  1. 暂无评论