On this page
Owl bird

How to set the focus on element and prevent from scrolling

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.

How can I prevent scrolling when setting focus on an element?

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="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 buttonActionWithoutScroll = document.getElementById('buttonActionWithoutScroll');

function setFocusWithoutScrolling() {
  exampleButton.focus({
    preventScroll:true
  });
  
  console.log(document.activeElement.nodeName);
}

buttonActionWithoutScroll.addEventListener('click', setFocusWithoutScrolling);

How do I detect if a browser supports preventScroll option?

To detect if a browser supports the preventScroll option in the focus() method, we need to determine when the browser is using the preventScroll option by attempting to use the focus() method on our test element and observing whether the browser tries to access the preventScroll option.

function isPreventScrollOptionSupported() {
  let isSupported = false;

  const divElement = document.createElement('div');

  divElement.addEventListener(
    'focus',
    (event) => {
      event.preventDefault();
      event.stopPropagation();
    },
    true
  );

  const spyOnOptions = Object.defineProperty({}, 'preventScroll', {
    get: () => {
      isSupported = true;
    }
  });

  divElement.focus(spyOnOptions);

  return isSupported;
}

Why is the “prevent scroll” feature not working in JavaScript?

The common root cause of preventing from scrolling is by using the preventDefault() method of the Event interface to stop the default scroll behavior.

You may test that scenario in below example.

Related posts

Comments

Leave a Reply

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)