Stefan Weiss
Stefan Weiss

Reputation: 313

Can I use scrollTop without writing a function?

I've got some trouble with my jQuery and was looking for some solutions to add something to my already existing slideDown function.

What looked very interesting to me is this question/answer from 2010 http://stackoverflow.com/questions/4034659/is-it-possible-to-animate-scrollop-with-jquery

The difference to that question is that I'm looking for a solution to scrollTop each time to a different <a> anchor.

In my example below, the <a href"#"> is suppose to move to the top.

Is that possible?

HTML

<div class="next_btn" id="next_btn_show_step_3">
    <a href="#"><?php echo $lang ['next']; ?></a>
</div>
<article class="order_form_step_3" id="banner_step_3">
</article>

jQuery

$(document).ready(function(){
  $("#banner_step_3").hide();

  $("#next_btn_show_step_3").click(function(e){
    $("#banner_step_3").slideDown(500);
    e.preventDefault();
  });
});

Upvotes: 1

Views: 165

Answers (2)

FiLeVeR10
FiLeVeR10

Reputation: 2165

jquery

$('.next_btn a').on('click', function(e) {//on link click
    var th = $(this);//get element
    th.parent().next('article').slideDown(500);//slide down
    $('html, body').animate({ scrollTop: th.offset().top }, 500);//scrollto link
    e.preventDefault();//prevent default
});

Upvotes: 0

tckmn
tckmn

Reputation: 59273

You could easily adapt that answer like this:

$("html, body").animate({ scrollTop: Math.floor($('#yourElement').offset().top) + "px" });

Upvotes: 2

Related Questions