Brad
Brad

Reputation: 202

Jquery: slideToggle, then scroll to div

I'm using slideToggle to display a div when a navigation button is clicked. It's working, but the div that I'm displaying is pretty tall, so you don't actually see much of it once it loads. The div sits directly beneath the button you use to trigger slideToggle. I would like to find a way to slideToggle the div, and then have the window scroll to the nav button, automatically displaying the entire previously hidden div.

<a href="#"> doesn't work as it tries to jump to the element before the slideToggle function has executed. Is there a way to have the window scroll to the element after slideToggle has completed?

You can see what I have so far here.

Click on the printables button to see what I'm talking about.

I also created a jsFiddle of the basic functionality, jsfiddle.

Upvotes: 2

Views: 4971

Answers (3)

L84
L84

Reputation: 46328

The two answers provided by Chad and Robert are both valid, however, I like to write it a bit differently.

Below is an example based on your jsFiddle. The JS is the part you need.

$(function() {
    $( "#button" ).on( "click", function() { //Click
	  $( "#content" ).slideToggle( "slow", function(){
			if ($(this).is(":visible")) { //Check to see if element is visible then scroll to it
				$('html,body').animate({ //animate the scroll
					scrollTop: $(this).offset().top - 25 // the - 25 is to stop the scroll 25px above the element
				}, "slow")
			}
		});
	  return false; //This works similarly to event.preventDefault(); as it stops the default link behavior
	});
});
/* This is for the example */
#button{
    display: block;
    margin: auto;
    margin-top:130px;
    height: 50px;
    width: 180px;
    background-color: #ccc;
}
#content{
    display: none;
    margin: 0 auto;
    height: 1200px;
    width: 170px;
    background-color: blue;
}
<!-- HTML for example -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" id="button">Click to expand content</a>
    
<div id="content">
</div>

Upvotes: 3

Chad
Chad

Reputation: 5428

Piggybacking off of Robert's answer, you could clean it up a bit by not using hashes.

$('a').click(function(event){
    event.preventDefault();
    $a = $(this);

    $(element).slideToggle(250, function(){
        $(window).scrollTop($a.offset().top);
    });
});

Upvotes: 2

Robert
Robert

Reputation: 386

$('a').click(function(event){
    event.preventDefault();

    $(element).slideToggle(250, function(){
        window.location.hash = "#content";
    });
});

Should work.

Upvotes: 2

Related Questions