user3939059 user3939059 - 2 months ago 6x
Javascript Question

Pop pre-pended div items in jQuery (on message receive)

I have a small function the uses a web socket to receive realtime updates. When a new response is received the function prepends a div in the html. I only want the updates to be shown in a window within the page, ie. only ~10 prepended divs should be showing at the most. Ideally I need to pop the oldest div before it overflows out of its parent div.

My question:

  1. How do I pop divs before they overflow the parent? Considering I will receive a response nearly every second or so, what is the most efficient way of doing this?


    <div class="content">
    <p>archienorman-thesis $ realtime_bitcoin</p>
    <div id="messages"></div>
    <!-- window content -->


    var total = 0;
    var btcs = new WebSocket('wss://');

    btcs.onopen = function () {
    btcs.send(JSON.stringify({"op": "unconfirmed_sub"}));

    btcs.onmessage = function (onmsg) {
    var response = JSON.parse(;
    var amount = response.x.out[0].value;
    var calAmount = amount / 100000000;
    var msgs = $('#messages .message');
    var count = msgs.length;

    if (count == 10) {
    $('#messages').prepend("<p class='tx'> Amount: " + calAmount + "</p>");


Make the container div overflow: hidden, check if there is overflow using JS scrollHeight and clientHeight.


#messages {
  overflow: hidden;


Remove your if statement and add this after your prepend() line:

$('#messages').prepend("<p class='tx'> Amount: " + calAmount + "</p>");
$('#messages').css("overflow", "scroll");
if($('#messages')[0].scrollHeight > $('#messages').height())
$('#messages').css("overflow", "hidden");

The above quickly makes #messages have the overflow: scroll property in order for the scrollHeight property to work. If there is extra scroll, then it deletes the element.

See Demo.


See my comment to your question. You should be removing last(), not first(). See the demo as an example -- try changing last() to first(), and it will not work.