0

I am working on this demo. Why am I not able to animate the #box-2 div to top on click?

$('#box-2').animate({scrollTop : 0},700);

$("#box-2").on("click", function(){
  $('#box-2').animate({scrollTop : 0},700);
});
body, html {
  width: 100%;
  height: 100%; }

.box{
  height: 100vh;
}
#box-1{
 background:khaki;
}
#box-2{
 background:red;
}
#box-3{
 background:green;
}
#box-4{
 background:orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<div class="col-md-12 box" id="box-1" > </div>
<div class="col-md-12 box" id="box-2" > </div>
<div class="col-md-12 box" id="box-3" > </div>
<div class="col-md-12 box" id="box-4" > </div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128

4 Answers4

1

fiddle codecheck this fiddleCheck this fiddle

You are clicking on #box-2 and expecting ot to be on top but it is already on top as you see it.

Sanjit Bhardwaj
  • 893
  • 7
  • 13
0

You need to specify $('html,body'), as described in this answer: https://stackoverflow.com/a/18780639/378779

kmoser
  • 8,780
  • 3
  • 24
  • 40
0

$('.mybtn').click(function(){
   $('html,body').animate({
      scrollTop: $('.blue').offset().top
   },'slow');
});
.red{
   background-color:red;
   height:100vh;
   }
   
   .blue{
      background-color:blue;
      height:100vh;
   }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='red'>
  <button class='mybtn'>Click here to scroll to blue div</button>
</div>
<div class='blue'></div>
0

It wasn't initially clear what you meant by:

animate the #box-2 div to top on click

Now that you've asked to actually move #box-2 to the top of the screen (which I'll interpret to mean "physically above #box-1), I'll refer you to this code:

$("#box-2").on("click", function(){
    $('#box-2:parent').each(function () {
        $(this).insertBefore($(this).prev('#box-1'));
    });
});

Which was answered here: Switch positions of 2 divs with jQuery

kmoser
  • 8,780
  • 3
  • 24
  • 40