Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Chrome from moving DOM element when showing text search result

If an element is overflow:hidden and we use the browser's text search functionality to find text that is within that element, but it's not visible, Chrome will move that element so that the search result will be visible to the user.

You can see this happening here: http://codepen.io/anon/pen/qdayVz Open the link in Chrome and search for text that is not in the visible, "CCC" for example, and you will see that Chrome will move the element to show the found text.

Here is a real world example: http://www.jssor.com/demos/full-width-slider.html -- Search for text that is not in the visible slide.

This does not happen in Firefox.

like image 873
b2238488 Avatar asked May 22 '15 14:05

b2238488


1 Answers

I was able to prevent this behavior using JavaScript.

When Chrome moves the #wide-child div to show the search text, what it is actually doing is scrolling the contents of #parent to scroll the search text into view. This triggers a scroll event as would be expected, which can be listened for. When the scroll event fires, it is then possible to reset the element's scroll value to whatever it should be (probably 0).

Example:

document.getElementById('parent').addEventListener('scroll', function(e){
  document.getElementById('parent').scrollLeft=0;
  console.log('Prevented scrolling');
});
#parent {
  width: 30px;
  overflow: hidden;
}

#wide-child {
  width: 500px;
}
<div id="parent">
  <div id="wide-child">
    AAAAAAA
    BBBBBBB
    CCCCCCC
    DDDDDDD
    EEEEEEE
  </div>
</div>
like image 136
John Stimac Avatar answered Sep 28 '22 03:09

John Stimac