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

84
Visualizações
How to scrollIntoView target id element of href to center of page using jQuery

I am curious how I can scroll the target id element of an anchor tag's href to the center of the page using the scrollIntoView method.

Here is my code so far:

$("a").click(function () {
    var target = $($(this).attr("href"));
  
    target[0].scrollIntoView({
      behavior: "smooth", 
      block: "center"
    })
  });

I am able to log the targeted element to the console and use other methods to change the targeted element but can't figure out how to center it when scrolling.

Here is a Codepen with an example of what I'd like to do but instead uses scroll-margin-top: 50vh.

Anything is appreciated, Thx.

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

0

Your code seems to be working for me. The issue may be with the href not being a valid css selector or the element not being available in the scope of your code.

Try adding console.log(target) to the callback function, or even logging target[0] and seeing if it is the desired target.

here is a working snippet of .scrollIntoView

(async () => {
  const $ = str => document.querySelector(str);
  const wait = t => new Promise(r => setTimeout(r, t));
  
  const section1 = $("section");
  const section2 = $("section:nth-of-type(3)");
  const options = {
    behavior: "smooth",
    block: "center"
  }
  while (true) {
    await wait(3000);
    section2.scrollIntoView(options);
    
    await wait(3000);
    section1.scrollIntoView(options);
  }
})();
body {
  margin: 0;
  height: 300vh;
  background: linear-gradient(black, lightgray);
  
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

section {
  height: 20px;
  width: 100%;
  background-color: rgba(30, 30, 255, 0.8);
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>

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