Scrolltop does not work when I use the Body element and yes HTML

2

I have not found an answer to the jQuery documentation. When I use body element for the animate with the scrollTop property I want to animate does not work.

Follow 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 still wanted to know why html and not body ?

    
asked by anonymous 11.04.2018 / 00:29

1 answer

0

By default, the overflow of the whole page is html . If you hide the overflow from html , you can enable body scrolling, but you must also set the height of body and html to 100% viewport (visible area of the document in the browser window) and enable overflow of body .

Without doing all these maneuvers , body is not scrollable, so animate can not scroll.

See an example of animate with 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íciododocumento<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><divclass="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>
    
11.04.2018 / 00:54