baband
baband

Reputation: 123

make the page scroll to put div on top

I'm building a page where I have some divs with different heights and a text inside them, I'd like to, when I click on div's text, to make the page move so that this div would get at the top of the screen.

I've searched around but what I find is often related to the fixed property, the thing is that I don't want to change the position property of the div, I'd like just the page to scroll automatically so that the div would be on top.

Do you have any advice on where I could start?

Thank you

.container {
  width: 100vw;
  height: auto;
}
.element {
  padding: 50px;
}
#element-1 {
  background-color: beige;
  height: 500px;
}
#element-2 {
  background-color: darkSeaGreen;
  height: 200px;
}
#element-3 {
  background-color: coral;
  color:  white;
  height: 800px;
}
#element-4 {
  background-color: MidnightBlue;
  color: white;
  height: 300px;
}
<div class="container">
  <div class="element" id="element-1">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-2">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-3">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-4">
    <h1>Some text</h1>
  </div>
</div>

Upvotes: 0

Views: 36

Answers (2)

Osman Durdag
Osman Durdag

Reputation: 965

If I correctly understand you, this will help you.

let divs = document.querySelectorAll(".element");
divs.forEach(div => {
    div.addEventListener("click", event =>{
        let divTop = div.offsetTop;
        window.scrollTo(0, divTop);
        console.log(divTop + " --- " + window.scrollY);
    });
});
.container {
    width: 100vw;
    height: auto;
}
.element {
    padding: 50px;
}
#element-1 {
    background-color: beige;
    height: 500px;
}
#element-2 {
    background-color: darkSeaGreen;
    height: 200px;
}
#element-3 {
    background-color: coral;
    color:  white;
    height: 800px;
}
#element-4 {
    background-color: MidnightBlue;
    color: white;
    height: 300px;
}
<div class="container">
  <div class="element" id="element-1">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-2">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-3">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-4">
    <h1>Some text</h1>
  </div>
</div>

Upvotes: 1

jaka_music
jaka_music

Reputation: 354

You would need to implement a function that does this

window.scrollTo(x, 0); 

where x is the position of the element. You can get that by using

let x = element.getBoundingClientRect().top;

Upvotes: 0

Related Questions