Search code examples
javascriptjqueryhtmlcssappendtext

How to put text on top of the other text in div


Hi I'm trying to make a comment section on my website and the code that I've written places the comment that I type in below the comment that is already typed in.

what I really want to do is that to place the newly typed comment above the old comments (like facebook or youtube or any other websites - when you type the comment in, it appears above the older comments (in the first row)) How do I do this by using javascript? Thank you. Below is the code that I've written.

<input id = "txtboxComment" type = "text" onkeyup = "typeComment(event)" placeholder = "Write a comment"/>
<div id = "comment"></div>
#txtboxComment { 
    float: left;
    width: 600px;
    height: 25px;
    margin-left: 10px;
    margin-top: 10px;}

#comment {
    border: solid 1px;
    float: left;
    width: 602px;
    height: auto;
    margin-left: 51px;
    margin-top: 10px;
}
function typeComment(e) {
    co = document.getElementById("txtboxComment");
    if (e.keyCode == 13) {
        co.click();
        document.getElementById("comment").innerHTML += "<pre>" + co.value  + "\n" + "</pre>";
}

Solution

  • Doing it using only javascript, since there is no jQuery in your code although you have tagged it

    function typeComment(e){  // Execute this function on enter key
        co = document.getElementById("txtboxComment");
        var _comment = document.createElement('pre'); //create a pre tag 
       if (e.keyCode == 13) {
            co.click();
            _comment.textContent = co.value; //put the value inside pre tag
            var _commentDiv = document.getElementById("comment");
            if(_commentDiv.firstChild === null){ // Will validate if any comment is there
            // If no comment is present just append the child
            document.getElementById("comment").appendChild(_comment) 
            }
            else{
            // If a comment is present insert the new 
           // comment before the present first child in comment section
            document.getElementById("comment").insertBefore( _comment,_commentDiv.firstChild );
            }
       }
    }
    

    Working Example