Jquery SlideToggle AND scroll

Andre picture Andre · Apr 12, 2011 · Viewed 8.2k times · Source

I'm having a problem with a slidetoggle link which appears at the bottom of my page. Effectively I want the user to click to show/hide the hidden div (which works fine)

The problem is the page doesn't scroll down to show the now, not hidden div

As a JQuery novice, is there any way to toggle the div and then center it on the page? Or at least scroll down, without things getting too complicated?

Thanks

Answer

lsuarez picture lsuarez · Apr 12, 2011

To perform this function, I'd recommend using a callback from your slideToggle call to set the document scroll using the scrollTop function. You'll be able to determine the value to the scrollTop setter by using offset to get the top position of the toggled container relative to the page. I'd suggest restricting the scroll behavior to only fire when the element is shown, not hidden.

In general, directly setting page scroll can be a slightly jarring UX. For that reason I'm actually going to give you code that animates scrollTop rather than straight up sets it using the scrollTop function, but this approach is not necessary as a direct call to scrollTop will equally position the page. I just think as a user I'd rather see a gradual scroll rather than a sudden positional change.

The code, for instance, would take the form:

$(".myShowHideLink").click(function() {
    $(".myToggleContainer").slideToggle("slow", function() {
        if ($(this).is(":visible")) {
            $(document).animate({
                scrollTop: $(this).offset().top
            }, "slow")
        }
    });
});

You may want to actually use $(this).offset().top - 50 or something similar so the scroll's set just a few pixels above the top of the container, but that's up to you. I find I don't like my elements to be butting up against the top border of the window.

I apologize I haven't created a test case for this as I'm shooting from the hip, but if it doesn't work as advertised, let me know and I'll adjust the code.