Keep Scroll at [last position after an AJAX request?

Asked

Viewed 21 times

-1

I am having difficulties in performing an activity that is to keep the scroll in the LAST position before the AJAX request.

//antes da requisição
 var scrollPosition = $('.cart').scrollTop();

==> REQUISIÇÃO

$.ajax({...})
.done(function () {
//depois da requisição
$('.cart').scrollTop(scrollPosition)
 })


When I perform this way the scroll keeps going up little by little with each request.

If I use Animate:

('.cart').animate({scrollTop: scrollPosition})

The code works however I need to make the scroll FIXED, because when using Animate, the scroll goes down from the top to the position.

If you also have a way that by refreshing AJAX do not change the scroll would be a good way.

I’ve tried by localStorage/sessionStorage and it doesn’t work.

What is leaving me with enough doubts is why the Scroll rises little by little with each refresh.

I can only use JQUERY

1 answer

0

you can create a fixed element right after where you will insert the result to do this way:

$(".click").click(function(){
  $([document.documentElement, document.body]).animate({
        scrollTop: $(".elementofixo").offset().top
    }, 2000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div class='container'>
<p>texto</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>texto</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>texto</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>texto</p>
<button class='click'>clik teste</button>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>texto</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>texto</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>texto</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class='elementofixo'></div>
</div>

This is just an event where you click the button that is in the middle of the screen and it does not return from the beginning but only from the scroll to the fixed element. but can help you call this event when add elements on the screen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.