Tech tip: how to set the focus on element and prevent from scrolling

    The HTMLElement.focus() method sets focus on the specified element. The focused element will receive keyboard and similar events by default. However, sometimes you would like to prevent from 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 developer console to see which element got focus state after activating each action. See a live example of how to set the focus and prevent from scrolling.

    HTML

    <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

    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);

    Leave a Reply