I am running into a little problem in Internet Explorer 11+. I have a scrollable container div (with "overflow-y:auto"), and a child div that is "contenteditable=true".
The problem that I'm running into is that whenever I try to programmatically focus on the child div (using element.focus()), Internet Explorer is automatically scrolling to the top of the parent div. I've been trying to find a workaround for IE to keep it from automatically scrolling to top, but have been unable to find one yet.
Here is a fiddle that illustrates the problem:
http://jsfiddle.net/grese/dvxh74fr/9/
HTML:
<div id="container">
<div id="editor" contenteditable="true">
<!-- sample text/html here -->
</div>
</div>
<button id="bold">bold</button>
CSS:
#container {
height: 250px;
overflow-y: auto;
border: 1px solid black;
}
#editor {
padding: 10px;
}
JS:
var container = document.getElementById('container');
var editor = document.getElementById('editor');
var bold = document.getElementById('bold');
// initially, scroll to bottom...
container.scrollTop = 200;
bold.addEventListener('click', function(e) {
e.preventDefault();
document.execCommand('bold');
// bring focus back to the editor...
// this is causing IE to scroll to the top of the container :(
editor.focus();
});
Steps to reproduce the problem:
If you go through the same steps in any other browser (Safari, Firefox, Chrome), you'll notice that the container does not scroll. It just stays at the same scroll position that it was before (which is the correct behavior).
Any ideas?
I have found a workaround. Instead of using ".focus" to focus the editor, I can use ".setActive" (which is only available in IE/Edge). The "setActive" method does not cause scrolling, but still "focuses" the element. I'm just doing feature-detection on the "setActive" function to determine whether or not we are in IE/Edge.
Here is the documentation for the "setActive" method:
https://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx
Here is a fiddle illustrating the solution:
http://jsfiddle.net/grese/dvxh74fr/11/
The JS solution:
var container = document.getElementById('container');
var editor = document.getElementById('editor');
var bold = document.getElementById('bold');
// initially, scroll to bottom...
container.scrollTop = 200;
bold.addEventListener('click', function(e) {
e.preventDefault();
document.execCommand('bold');
// bring focus back to the editor...
// use 'setActive' in IE/Edge so container does not scroll...
if (editor.setActive) {
editor.setActive(); // IE/Edge
} else {
editor.focus(); // All other browsers
}
});