Sukumar Dhoni Sukumar Dhoni - 1 month ago 7
HTML Question

Scroll up a div when showing which is initially on hide in Jquery?

I am new to jQuery.

I want to show a div based on its id, and while showing it I need to scroll up.

The div is initially hidden.

I tried running the following code but it is not scrolling up, it is showing at the bottom of the page and I need to scroll down to view the div.

html



<ul>
<li>
<a class="page-scroll" href="#registerDiv" id="register">Redeem</a>
</li>
</ul>

<section id="registerDiv" ng-controller="registerCtrl">
<!-- section will show when link is clicked -->
</section>


js



$(document).ready(function(){
$("#registerDiv").hide();
$("#register").click(function(){
$("#registerDiv").show("slow"); //need to slideUp here
});
});


Can somebody please help me fix this? Thanks in advance.

Answer

You just need to use .slideToggle().

Update: you need to display #registerDiv before you get .show().offset().top then hide and slideDown() after scrolling.

See example:

$(document).ready(function() {
  $("#registerDiv").hide();
  $("#register").click(function() {
    var dt = $("#registerDiv").show().offset().top
    $("#registerDiv").hide();
    $('html,body').animate({
        scrollTop: dt
      },
      'slow', function() {
        $("#registerDiv").slideDown();
      });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a class="page-scroll" href="#registerDiv" id="register">Redeem</a>
  </li>
</ul>
<p>some conetent before</p>
<p>some conetent before</p>
<p>some conetent before</p>
<p>some conetent before</p>
<p>some conetent before</p>

<section id="registerDiv" ng-controller="registerCtrl">
  something to show this section when clicked
</section>

<p>some conetent after</p>
<p>some conetent after</p>
<p>some conetent after</p>
<p>some conetent after</p>
<p>some conetent after</p>
<p>some conetent after</p>
<p>some conetent after</p>
<p>some conetent after</p>