November 2011

MSIE focus() quirk

This morning I was working on an issue where clicking a tab link would cause Internet Explorer to jump to a scroll position lower on the page as if to a named anchor.  The accessibility consultant I’m working with recommends that when a tab is activated, the focus should go to that tab’s content area.  I thought maybe the tab switching code was just missing e.preventDefault() or return false  on the click event but when I opened the file, the code to cancel the click was there. Eventually I deduced that the call to focus() was causing the jump but didn’t understand why exactly.

IE focus causes scroll

… and other assorted variations didn’t turn up many useful results in Google. I showed the issue to my coworker (and manager) and he immediately noticed that the browser was scrolling just far enough for the whole focused element to be within the viewport.  After some experimentation, we discovered this odd feature: when focusing an element that has a defined height, Internet Explorer will scroll so that the entire element is in view. We tested in IE7 – IE9 and got the same result every time. In a way, it kind of makes sense that the browser would ensure the element is visible but unfortunately there’s no way to cancel it as far as I can tell. As a workaround, avoid defining a height for the element receiving focus.