Scrolltop does not work when I use the Body element, but HTML

Asked

Viewed 156 times

2

I did not find an answer or in the jQuery documentation. Because when I use element "body" for Animate with the scrollTop property I want to animate does not work.

Follows my code

    function scrollPlacar() {
  $('body').animate({
    scrollTop: $(".placar").offset().top
  }, 1000);
}

But when I do it that way.

function scrollPlacar() {
  $('html').animate({
    scrollTop: $(".placar").offset().top
  }, 1000);
}

It works perfectly, but I’d still like to know why html and not the body?

  • put the other html codes to analyze please

  • Anderson your Body had height? Make sure your Body and HTML have values in height, guy html, body {height:100%}

1 answer

0


By default, the overflow of the whole page is from html. If you hide the overflow of html, you can activate the scroll of body, but it is also necessary to define the body and of html to 100% of the viewport (visible area of the document in the browser window) and enable the overflow of body.

Without doing all these maneuvers, the body is not manageable, and so the animate can’t make the roll.

See an example of animate with the body within the definitions explained above:

function scrollPlacar() {
  $('body').animate({
    scrollTop: $(".placar").offset().top
  }, 1000);
}
scrollPlacar();
html{
   overflow: hidden;
}
html, body{
   height: 100%;
}
body{
   overflow: auto;
   margin: 0;
}
.placar{
   background: red;
   height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Início do documento
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>
<div class="placar">animar até aqui</div>
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.