jquery – Preserve position on screen after shuffling items around – Education Career Blog

I have a long list of items where clicking on an item may move another related item to just below it. The problem is if the moved item appeared above the item being clicked, the move causes the page to scroll up and the mouse is no longer over the user center of focus. e.g.

  • Item1
  • Item2
  • Item3 – clicking this will move item1 below it
  • Item4

After the click:

  • Item2
  • Item3
  • Item1 – now below item3 which has shifted up on the screen (bad)
  • Item4

To do the move in jquery I use $(‘#item1’).insertAfter(‘$item3’); How do I keep Item3 at keep the same position from the top of the window?

Edit: Modified solution based on patrick-dw’s answer that keeps the mouse/screen position exactly over the clicked item is:

var pos = $('#item3').offset().top; 
$('#item1').insertAfter($('#item3');    
pos = pos - $('#item3').offset().top; 
// it may not have scrolled if the shuffling happened entirely below it
if (pos > 0) $(window).scrollTop($(window).scrollTop() - pos);

,

You should be able to do something similar to this assuming that there’s room to scroll.

$('#item1').insertAfter('#item3');
$(window).scrollTop( $(window).scrollTop() - $('#item3').outerHeight() );

This adjusts the scrollTop position by the amount of the outerHeight of item3.

Because the value for .scrollTop() represents the number of pixels hidden at the top, we reduce the number of hidden vertical pixels in order to scroll the page down returning the #item3 to its original position (or close to it).

,

Have a look at the scrollTo plugin. You could call it after clicking a list item.

Leave a Comment