0

So I'm working on a personal project which is just a simple status update. I'm constantly adding more functionality to it but I've been stuck for quite some time now. The problem is that whenever someone posts a new status I want that to appear on top, however the one on top is the first post created, which is a problem. This would mean you'd have to scroll down to the bottom to see the most recent post.

Screenshots:

Main page

Problem occurs, new element goes underneath old

Here is the javascript:

function statusPost() {
    status = document.getElementById("Status").value;

    if (status == "") {
        alert("Please write a status")
    }
    else {
        document.getElementById("Status").value = "";
        div = document.createElement("div");
        document.getElementById("container").appendChild(div);
        div.className = "update";
        div.innerHTML = status;
    }
}
DamianoPantani
  • 1,168
  • 2
  • 13
  • 23
Chaost
  • 55
  • 8

3 Answers3

2

instead of appending div at the end of container, you should prepend it using insertBefore

here is your modified code (I saved some references to elements to maintain readability)

var status = document.getElementById("Status");
var container = document.getElementById("container");

function statusPost() {
    if (status.value == "") {
        alert("Please write a status")
    } else {
        status.value = "";
        div = document.createElement("div");
        div.className = "update";
        div.innerHTML = status;
        container.insertBefore(div, container.firstChild);
    }
}
pwolaq
  • 6,343
  • 19
  • 45
1

Use insertBefore() instead of appendChild()

Check it out here:

W3school link

0

If you are using jquery you can use , prepend() method to achieve this. The data will come at top. Preppend

 <h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
</div>
$( ".inner" ).prepend( "<p>Test</p>" );

If you need this in Java Script Please try

insertBefore
VISHNU
  • 948
  • 8
  • 15