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>
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)
A less hacky solution might be to call
document.activeElement.blur()
in the event listener that triggers on clicks outside the <input />
element. activeElement
has great browser support.
You might also want to check in the event listener that the intended input currently has focus with something like
if (document.activeElement.id === 'foo') document.activeElement.blur()
or
if (document.activeElement.hasAttribute('bar')) document.activeElement.blur()
to ensure you're not randomly blurring some other active element whenever tapping outside your input field.
Turns out there's an even simpler solution. Unlike blur
, the mouseleave
event does fire on mobile Safari if you tap outside an input element. If you're using React, it's as simple as
<input onMouseLeave={e => e.target.blur()} />
Or, in plain JS:
const input = document.getElementById('foo')
input.addEventListener('mouseleave', e => e.target.blur())
event.currentTarget.blur()
may be even safer than event.target
(i.e. certain to be the intended input element) but I found both work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With