Stas Ponomaryov Stas Ponomaryov - 1 month ago 20
jQuery Question

ScrollTop not working after toggle

Cannot understand, why it doesn't scroll to element.

<div class="h3 showhide">...</div>
<div id="comments" class="inv" style="display:none;">...</div>
<script type="text/javascript">
$(document).ready(function () {
$('.main-content').on('click', '.showhide', function () {
$(".inv").toggle("slow");
$('html, body').stop(true, true).animate({
scrollTop: $('#comments').offset().top
}, 500);
return false;
});
});
</script>

Answer

You need to display #comments to get .offset().top using .show() then hide it using .hide().

See this example:

<script type="text/javascript">
  $(document).ready(function() {
    var comments_top = $('#comments').show().offset().top;


    $('.main-content').on('click', '.showhide', function() {
      if ($('#comments').is(":hidden")) {
      comments_top = $('#comments').show().offset().top;
      $('#comments').hide();
    }
      $(".inv").toggle("slow");
      $('html, body').stop(true, true).animate({
        scrollTop: comments_top
      }, 500);
      return false;
    });
  });
</script>
Comments