Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

81
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda