Reputation: 277
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>";
}
Upvotes: 0
Views: 2768
Reputation: 50326
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 );
}
}
}
Upvotes: 0
Reputation: 2825
You are appending the new content at the end of #comment
. If I understand the question correctly you want to prepend it. change this line document.getElementById("comment").innerHTML += "<pre>" + co.value + "\n" + "</pre>";
to
document.getElementById("comment").innerHTML = "<pre>" + co.value + "\n" + "</pre>" + document.getElementById("comment").innerHTML;
Upvotes: 0
Reputation: 113
i would get the div's content (all of the old comments) and asign that to variable x. Then get the inputs value, and asign that to variabl y. then set the div's content to y+x.
Upvotes: 0
Reputation: 200
Use
document.getElementById("comment").innerHTML = "<pre>" + co.value + "\n" + "</pre>" + document.getElementById("comment").innerHTML;
Upvotes: 1
Reputation: 226
I guess You want that your latest text should be placed on top of the other div,
JS
$("#pcontainer").prepend($('<p>This paragraph was added by jQuery.</p>').fadeIn('slow'));
Upvotes: 0