JQuery SlideToggle & Scrolling

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

The problem is that the page does not scroll down to show now, not the hidden div

As a jQuery beginner, is there a way to switch the div and then center it on the page? Or at least scroll down without making things too complicated?

thanks

+4
source share
1 answer

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.

+1
source

Source: https://habr.com/ru/post/1347732/


All Articles