1

To Be precise I need to scroll the window to the top of a div on click of a button.

I tried this:

$(".red").animate({"scrollTop": $(".red").scrollTop()},1000);

But didn't worked

Check out this jsfiddle: https://jsfiddle.net/gu8gx1ad/3/

Ahmad Nabi
  • 33
  • 1
  • 10

3 Answers3

2

You have to scroll html,body wrt your element like

$("html,body").animate({"scrollTop": $(".red").offset().top},1000);

Snippet,

function sc(w) {
  var cls = '';
  switch (w) {
    case 0:
      cls = '.green';
      break;
    case 1:
      cls = '.blue';
      break;
    case 2:
      cls = '.red';
      break;
  }
  cls && $("html,body").animate({
    "scrollTop": $(cls).offset().top
  }, 1000);

}
.green,
.red,
.blue {
  height: 200px;
  width: 300px;
  background: green;
  margin-top: 100px;
}
.red {
  background: red;
}
.blue {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#green" style="color:green;" onclick="sc(0)">green</a>
<a href="#blue" style="color:blue;" onclick="sc(1)">blue</a>
<a href="#red" style="color:red;" onclick="sc(2)">red</a>
<div class="green"></div>
<div class="blue"></div>
<div class="red"></div>
Rohan Kumar
  • 38,998
  • 11
  • 69
  • 99
0

The following code should do the trick for you. But it only works after the corresponding sections have their ID names not class names :

<a href="#green" style="color:green;" onclick="sc(0)">green</a>
<a href="#blue" style="color:blue;" onclick="sc(1)">blue</a>
<a href="#red" style="color:red;" onclick="sc(2)">red</a>
<div id="green" ></div>
<div id="blue" ></div>
<div id="red" ></div>



    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
        }
    });
Ashiq Muhammed
  • 298
  • 1
  • 9
-1

I'm not sure why you are trying to use JQuery to do this. All you need to do is give the dive an id and reference that in your link as per below.

<a href="www.domain.com/#red">GoToRed</a>

<div id="red">
    div content
</div>
LiffeyD
  • 103
  • 6
  • While this is simpler, it doesn't animate the page scrolling down as the jQuery version does. That may be a requirement the OP has. Also, just FYI the downvote isn't mine. – Rory McCrossan Jun 16 '17 at 09:51