While focus the element, page not get scrolled in firefox and IE?

Viewed 1782

I have tried to focus the element in my page using focus method. When the element is focusing, page scrolled automatically in to the focused element. But In firefox and IE browsers page not scrolled properly. So my focused element visible in bottom of the page.

Steps: Run the sample in chrome, element will be appear in middle of the page. In Firefox it will appear in bottom of the page.

How to resolve it?

setTimeout(() => {
  document.getElementById('parent-element').focus();
}, 10);
body {
  touch-action: none;
}

#target {
  height: 2000px;
  background-color: aliceblue;
}

#parent-element {
  max-height: 980px;
  width: 400px;
  left: 150px;
  top: 958px;
  display: inline-flex;
  background-color: #fff;
  box-shadow: 0 12px 40px 5px rgba(0, 0, 0, 0.26);
  max-width: 100%;
  min-width: 240px;
  height: auto;
  position: absolute;
}

.Child-element {
  border-bottom: none;
  padding: 18px;
  border-radius: 1px 1px 0 0;
  line-height: 30px;
  background-color: #fff;
}

.childcontent {
  display: block;
  width: 83%;
  color: rgba(0, 0, 0, 0.87);
}
<div id="target">
  <div id="parent-element" role="dialog" tabindex="-1">
    <div class="Child-element">
      <div class="childcontent">Am developer</div>
    </div>
  </div>
</div>

1 Answers

I can offer an experimental alternative solution I found while trying to figure out why Firefox doesn't center on focus().

scrollIntoView() will work for you if all you want to do is scroll the div into the center of the page. Again, its experimental, but I tested it in the latest Chrome and Firefox browsers and it works there.

You can use the following:

document.getElementById('parent-element').scrollIntoView({behavior: "instant", block: "center"});

You can check browser compatibility from these two resources. MDN and Can I Use

Related