Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent viewport from moving when removing DOM elements

I'm trying to implement an HTML infinite scroller in which at any given time there are only a handful of div elements on list (to keep the memory footprint small).

I append a new div element to the list and at the same time I'm removing the first one, so the total count of divs remains the same.

Unfortunately the viewport doesn't stay still but instead it jumps backwards a little bit (the height of the removed div actually). Is there a way to keep the viewport still while removing divs from the list?

I made a small self contained HTML page (well, it still needs JQuery 3.4.1) which exposes the problem: it starts by adding 5 divs and then it keeps adding a new one and removing the first one every 1 second

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

function removeit() {
  // remove first one
  var tiles = $(".tile");
  $(tiles[0]).remove();
}

function addit() {
  // append new one
  var jqueryTextElem = $('<div class="tile" style="height:100px;background-color:' + getRandomColor() + '"></div>');
  $("#inner-wrap").append(jqueryTextElem);
}

function loop() {
  removeit();

  addit();

  window.setTimeout(loop, 1000);
}

addit();
addit();
addit();
addit();
addit();

loop();
<div id="inner-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
like image 473
Gianluca Ghettini Avatar asked Sep 12 '25 03:09

Gianluca Ghettini


1 Answers

You can temporarily add position: fixed to the parent element:

  1. first add position: fixed to the parent;
  2. then remove the item;
  3. then remove position: fixed from the parent
like image 139
Rounin - Glory to UKRAINE Avatar answered Sep 13 '25 17:09

Rounin - Glory to UKRAINE