Nitche x Kris
Nitche x Kris

Reputation: 47

JQuery - Prevent scrolling when an element is shown

Im having a bit of trouble with this. How do I prevent the browser from scrolling when an element (a div) is shown.

I have a button (positioned on the bottom of the webpage) to show an element (positioned on the top of the webpage). If I scroll to the bottom of the page to click the button the browser automatically scrolls on top where the element is positioned. How do I prevent this?

Basically, when I scroll to the bottom of the webpage to show the element, I want to retain the browser's position in the bottom of the page. Is there anyway to do this?

Upvotes: 1

Views: 2827

Answers (3)

Nitche x Kris
Nitche x Kris

Reputation: 47

Just figured it out. It turns out that the answer I was looking for was in here: https://forum.jquery.com/topic/show-and-hide-causing-page-to-scroll-top

Then you use hide() it hides the element (using display:none) therefore stops taking space in the webpage. THe show() behaves as display:block and therefore starts taking space in the webpage. By doing this, the browser adjusts by teleporting (or scrolling) into the position where the element was shown or hide.

To prevent this from happening, the following methods can be used:

  • Give a fixed height dimension to the container, so if the contained element disappears, the height remains the same therefore no adjustments from the browser will trigger.

  • Add a 1 x (element_height) transparent gif next to the element

  • Use visibility:hidden and visibility:visible instead. (But this still takes up space even if the element is invisible)

Using the 1st option worked for me. Hope this helps :)

Upvotes: 1

ABE
ABE

Reputation: 706

You can set the position of element fixed, and now is show float cut off from his original position. Like this:

$('button').click(function(){
    $(element).css({'position': 'fixed', 'top': '30px'})
});

Upvotes: 0

Arnav Borborah
Arnav Borborah

Reputation: 11789

Set the CSS of the the HTML and BODY elements during this period to:

$("body,html").css({"overflow":"hidden"});

And after the event finishes, add the following jquery:

$("body,html").css({"overflow":"auto"});

This will disable the scrollBar during your event, and show it after it is done.

Upvotes: 1

Related Questions