Paragraph wrap callback for TinyMCE

When using TinyMCE if you only insert one line of text the selection will not be wrapped in paragraph tags. As soon as you hit return the selection will be wrapped in paragraphs but when you are handing the editor off to non-technical clients you can’t always be sure that’s going to happen.

We ran into this problem while building our form builder at UVa. Since the entire interface was being built with XSLT in Javascript the results coming out of the TinyMCE based message editor needed to be consistent. In the process I came up with the function that can be called as a save callback from TinyMCE.

This is the function that we will call from the callback. If you are using hak_tinymce make sure you have 0.6.3 and add it to the Callback Functions area.


function mceTagWrap(element_id, html, body) {
 html = trim(html);
 /*check that text starts and ends with tags if not wrap it in <p>s.  
   This only happens for single line text messages*/
  if(html.charAt(0) != "<" || (html.charAt(html.length - 1) != ">" || html.charAt(html.length -2) == "/")) {
	html = "<p>"+html+"</p>";	
  }
 return html;
}
function trim(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

The mceTagWrap() function will check if the results being sent back from TinyMCE start with < and end with > otherwise it will wrap it in <p></p>. It will also check if the second to last character is a / so a block opening with <img /> and ending with <br /> will still be wrapped in paragraph tags. trim() is just used by mceTagWrap() to remove unwanted spaces before and after the text block so that the first and last values are not spaces.

In order to call the function on save add this it to your TinyMCE.init().

save_callback:"mceTagWrap",

Comments:

  1. So, besides adding the code into the callback functions area, were do I have to save the save_callback.? Not sure were tiny_mce.init() is.

    — mel    Aug 20, 09:55 PM    #
  2. If you are using hak_tiny_mce there are two boxes in the admin area for the initialization (one for the article body and one for the excerpt).

    Just add the save_callback:“mceTagWrap”, there.

    hakjoon    Aug 20, 11:24 PM    #
  3. You rock! Thanks for this incredibly useful callback function.

    Jonathan Nicol    Aug 21, 11:49 PM    #
  4. wow, I’m impressed! why do i always come across things as useful as this when everyone else knows about it already? still, better later than never;)

    Mhunter    May 13, 04:16 AM    #

Leave a comment:

Please leave a comment.Your email address is required, but won't be displayed.

HTML will be removed. Basic formatting is available through Textile (see Textile Help). You may also use the toolbar to help you format your comments. Images are not allowed.