rich rich - 4 months ago 12
HTML Question

Bugs appending rows to table and scrolling to bottom of page

Code here and repeated below: http://codepen.io/anon/pen/rLvBbA

Click the "add rows" link repeatedly. Often it takes a few seconds to scroll to the bottom of the page after adding the rows, sometimes it does it immediately.

I don't know if it's that jquery's animate is sometimes doing the scroll immediately instead of over a duration, or if sometimes the browser is scrolling to the bottom immediately itself perhaps? The behaviour seems broken one way on Chrome and Safari (irregular) and differently on Firefox (seems to work on first page load but break up after that).

HTML:

<table>
</table>

<a href="javascript:(addRows())">Add rows</a>


CSS:

body {
padding: 100px;
}

td {
padding: 10px 20px;
border: 1px solid #ccc;
}

tr.level-WARN {
background-color: #FFB347;
}


Javascript:

$(document).ready(function() {
addRows();
addRows();
addRows();
addRows();
});

function addRows() {
for (var x = 0; x<5; x++) {
var row = $('<tr/>');
row.append($('<td/>').text('This is some table cell content.'));

if (Math.floor(Math.random() * 10) == 0) {
row.addClass('level-WARN');
} else {
row.addClass('level-INFO');
}
$('table').append(row);
}

$("html, body").animate({ scrollTop: $(document).height() }, 3000);
}

Answer

When you call:

addRows();

the previous animation could not be finished so you may add a jQuery stop in order to stop the currently-running animation and start a new one.

My snippet:

function addRows() {
  for (var x = 0; x<5; x++) {
    var row = $('<tr/>');
    row.append($('<td/>').text('This is some table cell content.'));

    if (Math.floor(Math.random() * 10) == 0) {
      row.addClass('level-WARN');
    } else {
      row.addClass('level-INFO');
    }
    $('table').append(row);
  }

  $("html, body").stop().animate({ scrollTop: $(document).height() }, 3000);
}
$(function () {
  addRows();
  addRows();
  addRows();
  addRows();
});
body {
  padding: 100px;
}

td {
  padding: 10px 20px;
  border: 1px solid #ccc;
}

tr.level-WARN {
  background-color: #FFB347;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<table>
</table>

<a href="javascript:(addRows())">Add rows</a>

Comments