Difference between scroll functions?

8

Is there a difference in using:

$(window).scrollTop(_Altura_);

Or

window.scroll(0,_Altura_);

Without controlling the position of the horizontal axis? (consider _Altura_ as a variable)

    
asked by anonymous 18.10.2017 / 13:43

1 answer

5

Both generate the same result the difference is that the jQuery .scrollTop uses window.scrollTo to execute which is the same as Window.scroll ( ) .

So we can conclude that window.scroll will perform faster because it is JS pure.

  

window.scroll - > window.scrollTo is effectively the same as this method.

Another point is that the function of jQuery , .scrollTop() , works with any element of DOM and it can also work as a getter when no parameter is passed, since that of vanilla , scroll , has no return and is applied to the Window .

$(() => {
  $("#window").on("click", event => {
    $(window).scrollTop(100);
  });
  
  $("#div").on("click", event => {
    $("div.demo").scrollTop(300);
  });
});
body {
  height: 1000px;
}

div.demo {
  border: 1px dashed red;
  height: 100px;
  overflow: auto;
}

div.demo p {
  height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="window">Scroll na window</button>
<button id="div">Scroll no elemento</button>
<div class="demo">
  <p>Stack Overflow em Português</p>
  <span>Estou a 300px do topo.</span>
</div>
    
18.10.2017 / 13:58