Search code examples
javascripthtmlcssfacebookpreview

Create a Facebook Post Preview


We have a website that allows customers to post pictures and videos directly to their Fanpage wall. Some of our customers request to have a "Post Preview" for the text, in order them to see how the words will be aligned after the text is submitted to Facebook.

So, my job is to implement this, what I did so far is:

The post text is written in textarea:

 <textarea id="fbMessage" name="message" placeholder="Enter your message here" rows="4" cols="47"></textarea>

I've created a div that will be used as a post preview, I've set its width to be similar to the actual div of the user content text in Facebook. Inside the div I've created a paragraph that will get the text, the paragraph font style is set exactly as in the Facebook user content text style:

<div id="preview" style="margin: 10px auto; width:366px; background: #EDEDED; border: solid 1px #CCC; padding: 10px; word-wrap: break-word;">
   <p id="previewText" style="font-size: 13px; font-family: 'lucida grande',tahoma,verdana,arial,sans-serif;">Facebook Preview</p>          
</div>

i use word-wrap: break-word; in order to force the text to wrap.

Last thing is a Javascript that will copy the text from the textarea to the preview div:

var form = document.getElementById('newFBForm');
var TheTextBox = document.getElementById("fbMessage");
var textAreaText = TheTextBox.value;

//Is used to preserve whitespace and new lines from the textarea to the div//    
previewText = textAreaText.replace(/\n/g, "<br/>").replace(/\s/g, "&nbsp");

document.getElementById('previewText').innerHTML = previewText;

My problem is, that sometimes I get my preview aligned just as it is on Facebook, here is an example:

  • On Facebook:

On Facebook

  • On my preview div:

My preview div

But sometimes I get a different alignment, here is the example:

  • On Facebook:

FB not good

  • On my preview div:

My preview div 2

You can see the problem with word11111111. This is only one example, but there are different text structures that produces different preview that the actual post.

Am I missing something? Or mybe something is wrong with my Implementation? Do you have ideas to improve it or add something to it?

UPDATE

This what happens when trying to use word-wrap: normal;:

ww normal


Solution

  • //Is used to preserve whitespace and new lines from the textarea to the div//    
    previewText = textAreaText.replace(/\n/g, "<br/>").replace(/\s/g, "&nbsp");
    

    You’re replacing every whitespace character (that is left after replacing \n) with a non-breaking space – of course that’ll give you weird effects even with word-wrap:normal … because you’re effectingly making every line of text to be one “word”, because the spaces in between the actual words are forbidden to be broken …