Ponnaveen S
Ponnaveen S

Reputation: 149

Animate while move to a new section in a same page in js

$('#skip-intro').on("click", function() {
  var header = $('.navbar').innerHeight();
  $("html, body").animate({
    scrollTop: $('#intro').offset().top - header
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#intro" id="skip-intro">Get to Know</a>
<div class="section-block" id="intro">
  ----content------
</div>

Here, Help me find out why animation property is not working while moving down to the below section.

Upvotes: 2

Views: 502

Answers (2)

Patrick Schocke
Patrick Schocke

Reputation: 1491

Original here: Find it here (But it's in german)

$('a[href*="#"]').on('click',function(e) {
 e.preventDefault();
 var target = this.hash;
 var $target = $(target);
 $('html, body').stop().animate({
  'scrollTop': $target.offset().top
 }, 900, 'swing', function () {
  window.location.hash = target;
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#exp">Href</a>
<div style="height:1000px; background:red;"></div>
<div id="exp" style="background:green; text-align:center;">jdaslkasd</div>

Upvotes: 2

Rajender Verma
Rajender Verma

Reputation: 399

Please use it like this.

<header class = 'navbar'>test</header>
<a href="#intro" id="skip-intro">Get to Know</a>
<div class="section-block" id="intro" style = "margin-top: 300px;">
----content------
</div>

Script

<script>
 $(document).ready(function() {
 $('#skip-intro').on("click", function(){
        var header = $('.navbar').innerHeight();
    console.log(parseInt($('#intro').offset().top) - parseInt(header))
        $("html, body").animate({ scrollTop: parseInt($('#intro').offset().top) - parseInt(header) }, 1000);
    });
  });

</script>

Please note in order to scroll animate to a certain div position it should be within that position for scroll to work, as per your html your div section block is already on top so it won't animate as it's currently visible on that position.

Upvotes: 0

Related Questions