2

I've come across some strange functionality on chrome, mobile.

When I try to focus on an element on chrome, it doesn't work when you try to just load the input, getItById and do .focus(). However, if you wrap it in an event listener attached to a button, and click the button with your mouse, it works fine.

So, I tried to trick it by seeing if you could call btn.click(), but that doesn't activate the .focus()

Have a go below: On mobile, chrome (at least for iOS), load the page. You should get an alert 'Clicked', but it won't focus on the input. Then, try clicking on the button. You will get both the alert AND the focus works.

I found this interesting and wanted to see if people knew of a workaround.

Link here - jsfiddle

<input id="input" type="text">
<button id="button">Button</button>

<script>
const btn = document.getElementById('button')

btn.addEventListener('click', () => {
  alert('clicked')
  const input = document.getElementById('input')
  input.focus()
})

btn.click()
</script>

Edit

Another thing I've noticed, is that if you put your phone go to sleep, and open it again, the focus() works without the click.

Edit 2 - added link for mobile

Hamish Johnson
  • 1,139
  • 12
  • 23
  • Is it just me or is it working just fine? – Sheshank S. Jan 05 '19 at 04:47
  • can you try setTimeout() function. setTimeout(function(){ input.focus() },10); – Anji Jan 05 '19 at 04:50
  • Possible Duplicate: [https://stackoverflow.com/questions/15859113/focus-not-working](https://stackoverflow.com/questions/15859113/focus-not-working) – Dimitris Jan 05 '19 at 04:55
  • Adding set timeout doesn't work - in fact, it breaks it even further as now when you click with the mouse, it doesn't activate the focus like it does without the settimeout – Hamish Johnson Jan 05 '19 at 05:03

0 Answers0