Mar 5, 2010

appending and prepending elements

intro
with AJAX user interfaces becoming more and more popular, users are getting used to things happening in real time on websites. take, for example, leaving a comment on a blog post. clicking “post comment” can submit a form that your server language (php) can handle and then reload the page with the comment posted. however this makes the entire page reload, which can take up more time than necessary, not to mention server resources to rebuild the entire page’s content. enter, [intlink id="109" type="post"]XMLHttpRequest[/intlink] and a little AJAX fun….

scenario
let’s assume you already have your [intlink id="109" type="post"]XMLHttpRequest[/intlink] function written and that it sends information to a postComment() function that will add the comment to the blog post. once you gave gotten your responseXML from the request you want to add the comment to the list of existing comments in real time.

solution
create the div that contains the comments and make sure to give it a unique id:

<div id="comment_container">
    <p>comment 1</p>
    <p>comment 2</p>
</div>

then simply get the dom element of the container div so you can add the element from the responseXML:

var new_comment = request.responseXML;
var comments = document.getElementById("comment_container");

now you have to decide if you want to add the element to the top or the bottom of the list. if you are sorting the comments with the newest at the bottom, you want to append the new comment:

comments.appendChild(new_comment);

this will add the dom element to the end of the list, attaching it to the beginning is a little trickier. there is no prependChild() method in javascript. instead you will have to use the insertBefore() method:

comments.insertBefore(new_comment, comments.firstChild);

combine this with some cool graphic effects (like fading in the new comment) and you can start to create a really appealing interface for your users.

Leave a comment