To execute this function, I would recommend using a callback from your slideToggle call to set the document to scroll using the scrollTop function. You can determine the value for the scrollTop setter using offset to get the top position of the overloaded container relative to the page. I propose restricting the scroll behavior only when firing when the element is displayed rather than hidden.
In general, direct page scrolling can be a bit sharp UX. For this reason, I'm actually going to give you a code that animates scrollTop, rather than directly setting it using the scrollTop function, but this approach is not required, since a direct call to scrollTop will equally position the page. I just think that as a user, I would rather see a gradual scroll rather than a sudden positional change.
The code, for example, will take the form:
$(".myShowHideLink").click(function() { $(".myToggleContainer").slideToggle("slow", function() { if ($(this).is(":visible")) { $(document).animate({ scrollTop: $(this).offset().top }, "slow") } }); });
You might want to use $(this).offset().top - 50 or something similar so that scrolling sets just a few pixels over the top of the container, but that is up to you. I find that I do not like my elements, which will be based on the upper border of the window.
Sorry, I did not create a test case for this, as I take off my hips, but if it doesnβt work as advertised, let me know and I will edit the code.
source share