Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!