0

I have three sections on my page, from top to bottom, A, B and C. You click on a button in section C. Now, some content is loaded in section A (above the button you clicked on), e.g. the content uses jQuery's slideDown() method.

Now, section C scrolls a little bit down (because the new content is making it do so). That's what I'd like to prevent. Is there a way that the browser automatically scrolls page to be at the exact same position as before the content loaded?

Anders
  • 8,307
  • 9
  • 56
  • 88
SwiftedMind
  • 3,701
  • 3
  • 29
  • 63

3 Answers3

1

If you want to make sure that the button does not move on the screen at all, even though content is added above it, this should do it:

$("mybutton").click(function() {
    //Save the vertical position of the button before content is added.
    var x1 = $(this).offset().top;
    //Do whatever the button is suppose to do, including adding the new content.
    doAllTheStuff();
    //See how much we moved.
    var x2 = $(this).offset().top;
    var dx = x2 - x1;
    //Scroll the same amount to keep the button from moving on the screen.
    $(document).scrollTop($(document).scrollTop() + dx);
});

If you are using this functionallity a lot on your page, you might want to wrap up the code a bit nicer. Here is a working JSFiddle.

This might also be interesting reading:

Community
  • 1
  • 1
Anders
  • 8,307
  • 9
  • 56
  • 88
1

You can scroll page to element when click on your button (probably your element).

$('html, body').animate({ scrollTop: $("#element").offset().top }, 2000);

Here an example: https://jsfiddle.net/kmser1uh/

UPDATE

A trick for scroll in the same exactly position is to save the offset of the element in the page after the scroll, and animate the scroll after button click.

The updated example:

https://jsfiddle.net/kmser1uh/2/

This is the save part:

var el;
var elPos;
var clr;

$(window).scroll(function(){
    clearTimeout(clr);
  clr = setTimeout(function(){
    $('.fullWidthBodyElement').each(function(){
    if ($(window).scrollTop() > $(this).offset().top && 
            $(window).scrollTop() < $(this).offset().top + $(this).height()) {
                    el = this;
                    elPos = $(window).scrollTop() - $(this).offset().top;
        }
        });
  },500);
});

And this the resume position:

$('html, body').animate({ scrollTop: ($(el).offset().top + elPos) }, 2000);
Baro
  • 5,300
  • 2
  • 17
  • 39
0

You Migt be using # in href attribute in anchor tag usejavascript:void(0);then you page will not get scrolled.