Want to set the focus on the element and prevent scrolling? Here you'll find out.
The HTMLElement.focus()
method sets focus on the specified element. The focused element will receive a keyboard and similar events by default. However, sometimes you would like to prevent scrolling the document to bring the newly-focused element into view. This could be useful when you want to check if the element is capable to receive focus.
Here is a simple example. Note: open the developer console to see which element got a focus state after activating each action. See a live example of how to set the focus and prevent from scrolling.
HTML code
<button type="button" id="buttonActionScroll">Activate me to focus on the button!</button> <button type="button" id="buttonActionWithoutScroll">Activate me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" style="margin-top: 500px;" id="exampleActionButton">Action</button> </div>
JavaScript code
const exampleButton = document.getElementById('exampleActionButton'); const buttonActionScroll = document.getElementById('buttonActionScroll'); const buttonActionWithoutScroll = document.getElementById('buttonActionWithoutScroll'); function setFocus() { exampleButton.focus({ preventScroll:false }); console.log(document.activeElement.nodeName); } function setFocusWithoutScrolling() { exampleButton.focus({ preventScroll:true }); console.log(document.activeElement.nodeName); } buttonActionScroll.addEventListener('click', setFocus); buttonActionWithoutScroll.addEventListener('click', setFocusWithoutScrolling);