Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 896
Pete Naylor Avatar asked Dec 20 '22 12:12

Pete Naylor


2 Answers

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);
  });
});​
like image 121
Jonathan Dixon Avatar answered Jan 10 '23 02:01

Jonathan Dixon


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>
like image 26
user3119274 Avatar answered Jan 10 '23 03:01

user3119274