article

Saturday, April 22, 2017

Smooth scroll to div using jQuery

Smooth scroll to div using jQuery
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Smooth scroll to div using jQuery</title>
            <style>
  h1{font-size: 40px;}
        p{ font-size: 35px;}
  #top a {padding: 10px;}
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div id="top">
                <a href="#section1">Go Section 1</a>|
                <a href="#section2">Go Section 2</a>|
                <a href="#section3">Go Section 3</a>|
                <a href="#section4">Go Section 4</a>|
                <a href="#section5">Go Section 5</a>
            </div>
            <div id="section1">
                <h1>Section 1</h1>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
           </div>
            <div id="section2">
                <h1>Section 2</h1>
                <a href="#top">BackToTop</a>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
            <div id="section3">
                <h1>Section 3</h1>
                <a href="#top">BackToTop</a>
    <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
   </div>
            <div id="section4">
                <h1>Section 4</h1>
                <a href="#top">BackToTop</a>
            <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
   </div>
            <div id="section5">
                <h1>Section 5</h1>
                <a href="#top">BackToTop</a>
            <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
   </div>
      </div>
    </div>
</div>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
     <script>
$(function() {
 $('a[href*=#]:not([href=#])').click(function() {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
  if (target.length) {
   $('html,body').animate({
     scrollTop: target.offset().top
   }, 1000);
   return false;
  }
 });
});
</script>
</body>
</html>

Related Post