Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Behavior of scrollIntoViewIfNeeded

I'm working on creating a web component that, given a list of elements that are focusable, automatically has accessible keyboard navigation.

Part of that is to have the active element scrolled into view if it isn't already, and to do this i'm using the Element.scrollIntoViewIfNeeded (in chrome, so support shouldn't be a problem).

I'm experiencing some weird behavior, that i can't quite figure out. I've created a minimal code sandbox to show the problem.

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next.focus();
        next.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        first.focus();
        first.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous.focus();
        previous.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last.focus();
        last.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);
body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app" class="app"></div>

    <script src="src/index.js"></script>
  </body>
</html>

the centerIfNeeded argument doesn't seem to be respected at all. At times it is respected the first time i focus an element that is outside of the viewport, but not the second time, and sometimes it is just completely ignored.

Is this expected behavior?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is that by default the focus() call will itself internally call scrollIntoView(), and the two calls will conflict.
To prevent that, you can pass the { preventScroll: true } option to your calls to focus().

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next?.focus({ preventScroll: true });
        next?.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        next?.focus({ preventScroll: true });
        first?.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous?.focus({ preventScroll: true });
        previous?.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last?.focus({ preventScroll: true });
        last?.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);
body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app" class="app"></div>

    <script src="src/index.js"></script>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda