Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior when focusing on an element [closed]

Clicking on the focus button makes #container move up 1 pixel:

<html>
   <body>
      <div style="overflow: hidden" id="root">
         <div style="margin: -1px" id="container">
            <div id="spacer" style="height: 2px"></div>
            <div id="focusable" tabindex="0">foo</div>
         </div>
      </div>
      <button onclick="document.getElementById('focusable').focus()">focus</button>
   </body>
</html>

A few observations: On Chrome/Edge, the height for #spacer needs to be at least 1px more than #container's negative margin.

On Firefox the height doesn't seem to matter, but if you execute the code as an HTML file and not from the snippet, you'll need to hard-reload (ctrl-f5) between runs otherwise #container stays in its shifted position.

like image 371
ExecutionSommaire Avatar asked Jan 25 '26 12:01

ExecutionSommaire


1 Answers

This is not mysterious -1px bug. When you focus an element normally, element.focus() (with the default preventScroll: false), the browser will scroll the page just enough to make that element fully visible.

Try this

<button onclick="document.getElementById('focusable').focus({preventScroll:true})">
  focus
</button>

This will place the DOM focus on the element without touching scroll positions

like image 129
Abdulla Nilam Avatar answered Jan 27 '26 01:01

Abdulla Nilam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!