Search code examples
javascriptiphoneinputsafari

Safari IOS - Input doesnt lose focus on click outside (Blur dont trigger)


I dont know why the blur event does not trigger when I click outside the input text (on the paragraph in yellow). So the keyboard cant close. The only way I can trigger it is when I click on the body (in blue in the snippet).

I have put many console.log for debugging.

What is even more weird is that when I remove the event click on the document, the click on body dont work anymore!

The problem occurs on Safari IOS. I have tested on Iphone 6.

Any idea ?

Thanks for your help

<!DOCTYPE html>
<html lang="en" style="height:200px; background:blue">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>

<body style="height:200px; background:gray">

    <form action=""  style="background:purple">
      <input type="text" name="test" id="test">
    </form>
    <p  style="height:50px; background:yellow" >Paragraph</p>
    <script>
        $(document).ready(function() {

            $(document).on('click', function() {
                console.log('document click')
            });

            $('input').click(function(event) {
                console.log("input click");
            });

            $('input').blur(function(event) {
                console.log('input blur');
            });

            $('input').focusout(function(event) {
                console.log('input focustout')
            });

            $('body').on('click', function(event) {
                console.log('body click');
                console.log(event);
            });

        });
    </script>
</body>

</html>


Solution

  • I found a hack for this:

    document.body.firstElementChild.tabIndex = 1
    

    This makes the first element in the body focusable thus when you click "outside" the input it loses focus. At the same time you don't see any visual glitches on that focused element because there is not style defined (unless your first body child element is something other than div)