1

My question is this:

I have a main view and inside it I have a div where another view is loaded with jquery. When I load the div with jquery, the result is correct, but it puts me back at the top of the view and my div is down How can I make the div content load without moving the current scroll position?

html:

<html><body>
...
<div class="col-md-12" id="productList"></div>
...
</body></html>

jquery:

function loadProduct(){
    var op_sort = document.getElementById('op_sort').value;
    var op_dir = document.getElementById('op_dir').value;
    $.get("showProductsListSorted",
        {op_sort: op_sort, op_dir: op_dir},
        function(response){
            $('#productList').html(response);
        }
);

Thanks in advance.

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
Úrsula
  • 21
  • 4

2 Answers2

1

after you load the content, make the change:

...
$('#productList').html(response);
$('html, body').animate({ scrollTop: $('#productList').offset().top }, 'fast');

That will scroll the window to your element, but the location of the scrollbar probably will not be exactly where it was prior to loading.

UPDATE

even better, try using the load function:

$( "#productList" ).load( "showProductsListSorted",
        {op_sort: op_sort, op_dir: op_dir}, function() {
  $('html, body').animate({ scrollTop: $('#productList').offset().top }, 'fast');
});

SO has a nice discussion on $.get() vs $.load() here: AJAX jQuery.load versus jQuery.get

UPDATE 2

To keep the scrollbar exactly where it was, use:

var initialScrollTop=$('html, body').scrollTop();
$( "#productList" ).load( "showProductsListSorted",
        {op_sort: op_sort, op_dir: op_dir}, function() {
  $('html, body').animate({ scrollTop: initialScrollTop }, 'fast');
});
Community
  • 1
  • 1
longestwayround
  • 979
  • 9
  • 13
0

Thanks to Longestwayround for his answer, it is an option that I will use in other tasks. But what I was really looking for was I wrestled a bear once's suggestion, with which using javascript and an Id, directly places the view in position.

JavaScript:

$( "#productList" ).load("url",
    {op_sort: op_sort, op_dir: op_dir, op_page: op_page, id_pro: id_pro, id_cat: id_cat},
    function() {
        $('#focusAfterSort').focus();
    }
);

Html:

    <div class="col-md-12" id="focusAfterSort" tabindex="1">
Úrsula
  • 21
  • 4