Scrolling to last appended item breaks after X appended items

Viewed 68

I have a scrollable div where i append dynamically some items, on each appended item i scroll to the last one to keep the last item ever visibly, but after i add X items the scroll just breaks by scrolling down and up.

function addProdotto(prodotto) {
  $(".prodotti").append(
    $("<div>", { class: "prodotto" })
      .text(prodotto.desc)
      .append(
        $("<span>").text(prodotto.prezzo),
        prodotto.promo &&
          $("<div>", { class: "promo" })
            .text(prodotto.promo.desc)
            .append($("<span>").text(prodotto.promo.prezzo))
      )
  );
  $(".prodotti").animate({ scrollTop: $(".prodotto").last().offset().top });
}

$('.addProducts').on('click', function() {
addProdotto({ desc: "TEST", prezzo: "2.00€", promo: { desc: "PROMO 20%", prezzo: "0.20€" } });
})
.header {
    background-color: red;
    height: 80px;
}

.prodotti {
    padding: 1rem;
  height: calc(100vh - 160px);
  overflow: auto;
}

.bottom {
    height: 80px;
    background-color: blue;
}
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous" />
    <button type="button" class="addProducts">
      ADD
    </button>
    <div class="row">
      <div class="col-sm-4">
        <div class="row">
          <div class="col-sm-12 header">

          </div>
          <div class="col-sm-12 main">
            <div class="prodotti">

            </div>
          </div>
          <div class="col-sm-12 bottom">

          </div>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

As you could see after you add lot of items the scroll just breaks and stop scrolling to the last item and just goes up and down..

1 Answers

I've solved the issue by doing the .animate directly on $('.prodotti') where i append the new item and by using .prop('scrollHeight') instead so my solution looks like this:

function addProdotto(prodotto) {
  $(".prodotti").append(
    $("<div>", { class: "prodotto" })
      .text(prodotto.desc)
      .append(
        $("<span>").text(prodotto.prezzo),
        prodotto.promo &&
          $("<div>", { class: "promo" })
            .text(prodotto.promo.desc)
            .append($("<span>").text(prodotto.promo.prezzo))
      )
  )  .animate({ scrollTop: $(".prodotti").prop("scrollHeight") }, "slow");
}
Related