简体   繁体   中英

Screen not scrolling down when using JQuery slidetoggle()

I have a site where there is a called .slidingDiv which when the anchor .show_hide is clicked it appears and slides down which is great when it's the only content on the page.

If there is other content above this div it doesn't scroll down and show. Instead it shows the div but it is out of site, so it does actually work but not push the rest of the content up.

Here's the JQuery:

<script type="text/javascript">

$(document).ready(function(){

        $(".slidingDiv").hide();
        $(".show_hide").show();

    $('.show_hide').click(function(){
    $(".slidingDiv").slideToggle(), 1000;
    scrollTop: $(this).offset().top
    });

});

</script>

Many thanks

Pete

Setting scrollTop in the callback of the slideToggle function or after the slideToggle function has been called (as you have did) results in jumpy behavior, at best. If you are looking for a smooth animation it is best to initiate the slide then animate the page to scroll down. This is demonstrated by this fiddle . Here is the js:

$(document).ready(function() {
  $(".slidingDiv").hide();
  $(".show_hide").show();

  $('.show_hide').click(function() {
    $(".slidingDiv").slideToggle(1000);
    $('html, body').animate({
      scrollTop: $(".slidingDiv").offset().top + $('window').height()
    }, 2000);
  });
});​

Just make a check before scrollTop

 <script type="text/javascript"> $(document).ready(function(){ $(".slidingDiv").hide(); $(".show_hide").show(); $('.show_hide').on('click',function(){ $(".slidingDiv").slideToggle(function(){ if($('.slidingDiv').height() > 0) { $('html, body').animate({ scrollTop: $(".slidingDiv").offset().top }, 1000); } }); }); }); </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM