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

164
Vistas
smooth scroll to center of <div> – JS

I have an element on my website with: class="F4", above this element there is a button and when I click this button I want the following thing to happen:

The element changes its size and the website smoothly scrolls so that the element is in the center of the viewport.


This is what I was able to do: (Fiddle here: https://jsfiddle.net/axm8shdo/4/)

function enlargeF4(){
    document.querySelector(".F4").style.width = "300px";
  document.querySelector(".F4").style.height = "300px";
  
  setTimeout(() => {
    document.querySelector(".F4").scrollIntoView({
            behavior: 'smooth',
      block: 'center',
        });
    }, 500);
}
* {
  margin: 0;
}

.spacer {
  background-color: lightgrey;
  width: 100%;
  height: 500px;
}

button {
  margin: 10px;
}

.F4 {
  width: 100px;
  height: 100px;
  background-color: yellow;
  
  transition-timing-function: ease-in-out;
    transition-duration: .5s;
}
<div class="spacer"> Scroll down! ;)</div>

<button onclick="enlargeF4()">run: enlargeF4()</button>
<div class="F4">Figure 4</div>

<div class="spacer"></div>

↑ This is roughly what I want, but not really.

  1. I want the change in size and the scroll to happen simultaneously. – I added a timeout because without it, my scrip doesn't scroll to the centre of my element, but I really don't want there to be a timeout.
  1. In some browsers, like Firefox, the scroll is really smooth, but in others, like Safari, the page just jumps and there is basically no scroll effect. – I need a smooth scroll in all browsers.

How can I achieve the desired effect?


Possible Solution:

I somehow find out how many pixels I have to scroll down and then using setInterval() and window.scrollBy() I smoothly scroll to the center of the div. – I think I can write such an interval, but first I have to somehow get the exact amount of pixels that I have to scroll down, or up, and I don't know how to do that.

Also: Maybe there is a more easy, or better way, of solving this…

Thank You!

about 4 years ago · Juan Pablo Isaza
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