Stefan Weiss
Stefan Weiss

Reputation: 313

How to add scroll up function to slideDown with 1 click?

I've got a working slideDown function which I'm using to show divs once the user clicked the button.

The divs are quite height and it would give a better overview if I would be able to scroll them to the top of the page. How can I activate and add a scroll up function to the existing slideDown function which will work simultaneously with just one click?

jQuery

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

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

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>

Upvotes: 0

Views: 115

Answers (2)

FiLeVeR10
FiLeVeR10

Reputation: 2265

jquery

$("#banner_step_3").hide();
$("#next_btn_show_step_3 a").on('click', function(e) {//on link click
    var ts = $(this).attr('href');//get element
    $(ts).slideDown(500);//slide down
    $('html, body').animate({ scrollTop: $(ts).offset().top }, 500);//scrollto element
    e.preventDefault();//prevent default
});

html

<div class="next_btn" id="next_btn_show_step_3">
    <!-- added id as href -->
    <a href="#banner_step_3">next</a>
</div>
<article class="order_form_step_3" id="banner_step_3">hey yo</article>

This could be made much easier if you were to post a working example.

made a fiddle: http://jsfiddle.net/filever10/6ZcjK/

Upvotes: 1

Commodore Timo
Commodore Timo

Reputation: 277

Get the offset top value of the div and use jQuery .scrollTop()

<script>
    $(document).ready(function(){
        $("#banner_step_3").hide();
        $("#next_btn_show_step_3").click(function(e){
            $("#banner_step_3").slideDown(500, function(){
                var offsetTop = $('#banner_step_3').offset().top;
                $("html").scrollTop(offsetTop);
            });
            e.preventDefault();
        });
    });
</script>

Upvotes: 1

Related Questions