jQuery scroll Top

scroll to any div using jquery

by divyanshu013

HTML

<button id="button4">
  Go to div3
</button>
<div id="div1">
  <h1>
div1
</h1>
</div>
<div id="div2">
  <h1>
div2
</h1>
</div>
<div id="div3">
  <h1>
div3
</h1>
</div>
<div id="div4">
  <h1>
div4
</h1>
</div>
<button id="button2">
  Go to div2
</button>

CSS

div {
  margin: auto;
  border: 2px solid teal;
  width: 500px;
  height: 500px;
  padding: 5px;
}

JavaScript

$(document).ready(function() {

  $('#button4').click(function() {
  	// check if the div lies below the viewport
    if ($('#div3')[0].getBoundingClientRect().top > 0) {
    	// in this case we need to add shift
      var shift = $(window).height() - $('#div3').height();
    } else {
      var shift = 0;
    }
    $(window).scrollTop($('#div3').offset().top - shift);
  });
  $('#button2').click(function() {
  	// check if the div lies below the viewport
    if ($('#div2')[0].getBoundingClientRect().top > 0) {
      var shift = $(window).height() - $('#div2').height();
    } else {
    	// since we need to scroll up there is no need to add shift hence 0
      var shift = 0;
    }
    $(window).scrollTop($('#div2').offset().top - shift);
  });

});