Add a preview to your WordPress comment box

Yesterday I was browsing around the blog world and came across this posting on keeping a clean desk. I found the topic interesting enough to leave a comment, but that’s not really the point. What I saw as I typed was that below the comment box was a preview of what I was typing. This is one of those things that I couldn’t believe I hadn’t thought of for any of my blogs so I went out and got it working on one of my sites. Hopefully within the next couple of days I’ll get it working here as well. A couple of minutes adding the code and it’s working here as well.

Adding the preview area
On most blogs this will go in the comments.php file in whatever theme you’re using.

The first thing you need to do is add a hidden div that will become your comment box. It must have an ID but can also use a class if you’re already using a class to style your comments.

[html]

Comment Preview

[/html]
The comment_preview_wrapper div is what we’re going to show using javascript code in just a second. The comment_preview div is where we’ll actually put the preview.

Line four is blank intentionally just to note that the comment_preview div is empty right now. We’ll use the innerHTML property to fill it as the user types.

The Javascript
The following JS code goes in the onkeyup property of the comment textarea.

[javascript]document.getElementById(‘comment_preview_wrapper’).style.display=’block’; document.getElementById(‘comment_preview’).innerHTML = this.value.replace(/(\n)|(\r\n)/g, ‘
‘); [/javascript]

You’ll notice that we replace any line breaks with <br /> tags so that the preview will have line breaks where it should.

The textarea should look like this, although it may have an ID or class depending on what theme you’re using.
[html]