Show word count, remaining char, adding additional event’s function for TinyMCE editor

I have described at my another blog how to set up TinyMCE editor to any application. charcount1I added some functions that shows the char remaining values in the initTinyMCE.js file. if you want to add some other function you can do that the same way.the function is -

setup :function(ed) {
/*ed.onClick.add(function(ed, e){ alert(‘click’);   });  */
ed.onBeforeSetContent.add(function(ed, o) {
// o.content = o.content.replace(/<p>/i, “”);
// o.content = o.content.replace(‘</p>’, “”);
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,”"); ///remove <p> and </p>
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text); //_path_row is used for showing text at status bar of editor
}
);

ed.onKeyUp.add(function(ed, e) {
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,”");
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
if(strip.length > characterLimit){
strip = strip.substring(0,characterLimit);
tinyMCE.execCommand(‘mceSetContent’,false,strip);
alert(“The length of your message is “+strip.length +” the max num of characters \n allowed for this text Area is “+characterLimit);
}
});

}

This new version (3+) introduce tinyMCE.activeEditor.getContent() function for getting the content value. for old version use – tinyMCE.getInstanceById(‘txaMainline’).getBody().innerHTML

tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text); is used for setting message at the editor status bar.

tinyMCE.execCommand(‘mceSetContent’,false,strip); is used for dynamically set the new value. when editor exceed the max value, the value from zero to max char is set to the content.

so the full text of initTinyMCE.js is

————— initTinyMCE.js
var characterLimit = 2000;
tinyMCE.init({
theme : “advanced”,
mode : “textareas”,
plugins : “searchreplace,print,paste”,
entity_encoding:”named”,
entities : “&quot;,34,&nbsp;,160,&amp;,38,&cent;,162,&euro;,8364,&pound;,163,&yen;,165,&copy;,169,&reg;,174,&trade;,8482,&permil;,8240,&lt;,60,&gt;,62,&le;,8804,&ge;,8805,&deg;,176,&minus;,8722″,
theme_advanced_buttons1 : “print,search,replace,separator,undo,redo”,
theme_advanced_buttons2: “”,
theme_advanced_buttons3 : “”,
theme_advanced_toolbar_location : “top”,
theme_advanced_toolbar_align : “left”,
theme_advanced_path_location : “bottom”,
extended_valid_elements : “a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]“,
theme_advanced_resize_horizontal : true,
theme_advanced_resizing : true,
nonbreaking_force_tab : false,
apply_source_formatting : false,
width : 400,
debug : false,
//handle_event_callback : “myHandleEvent”,
cleanup : true,
theme_advanced_path : false,
setup :function(ed) {
/*ed.onClick.add(function(ed, e){ alert(‘click’);   });  */
ed.onBeforeSetContent.add(function(ed, o) {
// o.content = o.content.replace(/&lt;p&gt;/i, “”);
// o.content = o.content.replace(‘&lt;/p&gt;’, “”);
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,”");
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
}
);

ed.onKeyUp.add(function(ed, e) {
var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,”");
var text = strip.split(‘ ‘).length + ” Words, ” +  strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
if(strip.length > characterLimit){
strip = strip.substring(0,characterLimit);
tinyMCE.execCommand(‘mceSetContent’,false,strip);
alert(“The length of your message is “+strip.length +” the max num of characters \n allowed for this text Area is “+characterLimit);
}
});
}

});

Advertisement

19 Responses to Show word count, remaining char, adding additional event’s function for TinyMCE editor

  1. Lang Nguyen says:

    Yes run good but when i need modidy my data when load TyniMCE and data fill but it alert
    1 Words, 0 Characters. You have 2000 Chracter remaining.

  2. rajibinfo says:

    Thanks Nguyen,
    this message should not show be as alert it should show at the bottom of textarea as a status. this line
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    is responsible for shows that message at bottom.
    I used version 3_2_1_1. It works for me.

    Rajib

  3. [...] After having a look around at the limited number of different solutions I was able to find, I decided to base our version on the one provided here. [...]

  4. Roy says:

    This looks really good. However, I can’t seem to get it to work. I really appreciate any help you can give me. Here is my configuration settings.

    var characterLimit = 2000;
    tinyMCE.init({
    // General options
    mode : “textareas”,
    theme : “advanced”,
    plugins : “tinyautosave,safari,save,preview,searchreplace,print,fullscreen”,

    // Theme options
    theme_advanced_buttons1 : “tinyautosave,save,print,fullscreen,preview,replace”,
    theme_advanced_buttons2 : “”,
    theme_advanced_buttons3 : “”,
    theme_advanced_buttons4 : “”,
    theme_advanced_toolbar_location : “top”,
    theme_advanced_toolbar_align : “left”,
    theme_advanced_statusbar_location : “bottom”,
    theme_advanced_resizing : true,

    // Example content CSS (should be your site CSS)
    content_css : “css/example.css”,

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : “js/template_list.js”,
    external_link_list_url : “js/link_list.js”,
    external_image_list_url : “js/image_list.js”,
    media_external_list_url : “js/media_list.js”,

    // Replace values for the template plugin
    template_replace_values : {
    username : “Some User”,
    staffid : “991234″
    }

    setup :function(ed) {
    /*ed.onClick.add(function(ed, e){ alert(’click’); }); */
    ed.onBeforeSetContent.add(function(ed, o) {
    // o.content = o.content.replace(/<p>/i, “”);
    // o.content = o.content.replace(’</p>’, “”);
    var strip = (tinyMCE.activeEditor.getContent()).replace(/(]+)>)/ig,””);
    var text = strip.split(’ ‘).length + ” Words, ” + strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    }
    );

    ed.onKeyUp.add(function(ed, e) {
    var strip = (tinyMCE.activeEditor.getContent()).replace(/(]+)>)/ig,””);
    var text = strip.split(’ ‘).length + ” Words, ” + strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” Chracter remaining.”;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    if(strip.length > characterLimit){
    strip = strip.substring(0,characterLimit);
    tinyMCE.execCommand(’mceSetContent’,false,strip);
    alert(”The length of your message is “+strip.length +” the max num of characters \n allowed for this text Area is “+characterLimit);
    }
    });
    }

    });

    • rajibinfo says:

      sorry for late answer, anyway you have some other js file. I can give one suggestion you. please see the error console and find out any javascript error occurs. if there is no error then it should work.

  5. leon says:

    Can i place the “var characterLimit = 2000;” to a special textarea. So i can use different Limits for more textareas?

    Thanx, Leon

  6. Joan says:

    very thks! that’s great and it is very functional. The only think is that posting the code, wp change de ” to beautifuly ” and turns crazy my ide!

    just it.. thks a lot

    Joan

  7. Scott S says:

    Thanks for posting. It works pretty well. The only issue I noticed is that

    tinyMCE.execCommand(‘mceSetContent’, false, strip);

    does not maintain the previous formatting. Is there a way to maintain the formatting (that is, the html tag elements)?

    Thanks!

    Scott

  8. Rick says:

    Is there an easy way to get it not to count the html tags?

    Thanks
    Rick

  9. Rick says:

    Ignore last comment I cannot count!! Sorry. Just having issues with ’

  10. Figo Mago says:

    Thanks for the post. The only thing I changed was to execute the parsing after content loading to avoid displaying a word count of “1 word o characters” even though there was content in the textarea.

    I did this by changing “ed.onBeforeSetContent.add(…”
    to “ed.onSetContent.add(…”

    Works perfectly,
    Thanks again
    Figo

  11. lokesh says:

    It is not working for me .I just simply trying to show some text on status bar.I am pasting code here.

    tinyMCE.init({
    mode : “textareas”,
    theme : “advanced”,
    entities : “160,nbsp,38,amp,34,quot,162,cent,8364,euro,163,pound,165,yen,169,copy,174,reg,8482,trade,8240,permil,181,micro,183,middot,8226,bull,8230,hellip,8242,prime,8243,Prime,167,sect,182,para,223,szlig,8249,lsaquo,8250,rsaquo,171,laquo,187,raquo,8216,lsquo,8217,rsquo,8220,ldquo,8221,rdquo,8218,sbquo,8222,bdquo,60,lt,62,gt,8804,le,8805,ge,8211,ndash,8212,mdash,175,macr,8254,oline,164,curren,166,brvbar,168,uml,161,iexcl,191,iquest,710,circ,732,tilde,176,deg,8722,minus,177,plusmn,247,divide,8260,frasl,215,times,185,sup1,178,sup2,179,sup3,188,frac14,189,frac12,190,frac34,402,fnof,8747,int,8721,sum,8734,infin,8730,radic,8764,sim,8773,cong,8776,asymp,8800,ne,8801,equiv,8712,isin,8713,notin,8715,ni,8719,prod,8743,and,8744,or,172,not,8745,cap,8746,cup,8706,part,8704,forall,8707,exist,8709,empty,8711,nabla,8727,lowast,8733,prop,8736,ang,180,acute,184,cedil,170,ordf,186,ordm,8224,dagger,8225,Dagger,192,Agrave,194,Acirc,195,Atilde,196,Auml,197,Aring,198,AElig,199,Ccedil,200,Egrave,202,Ecirc,203,Euml,204,Igrave,206,Icirc,207,Iuml,208,ETH,209,Ntilde,210,Ograve,212,Ocirc,213,Otilde,214,Ouml,216,Oslash,338,OElig,217,Ugrave,219,Ucirc,220,Uuml,376,Yuml,222,THORN,224,agrave,226,acirc,227,atilde,228,auml,229,aring,230,aelig,231,ccedil,232,egrave,234,ecirc,235,euml,236,igrave,238,icirc,239,iuml,240,eth,241,ntilde,242,ograve,244,ocirc,245,otilde,246,ouml,248,oslash,339,oelig,249,ugrave,251,ucirc,252,uuml,254,thorn,255,yuml,914,Beta,915,Gamma,916,Delta,917,Epsilon,918,Zeta,919,Eta,920,Theta,921,Iota,922,Kappa,923,Lambda,924,Mu,925,Nu,926,Xi,927,Omicron,928,Pi,929,Rho,931,Sigma,932,Tau,933,Upsilon,934,Phi,935,Chi,936,Psi,937,Omega,945,alpha,946,beta,947,gamma,948,delta,949,epsilon,950,zeta,951,eta,952,theta,953,iota,954,kappa,955,lambda,956,mu,957,nu,958,xi,959,omicron,960,pi,961,rho,962,sigmaf,963,sigma,964,tau,965,upsilon,966,phi,967,chi,968,psi,969,omega,8501,alefsym,982,piv,8476,real,977,thetasym,978,upsih,8472,weierp,8465,image,8592,larr,8593,uarr,8594,rarr,8595,darr,8596,harr,8629,crarr,8656,lArr,8657,uArr,8658,rArr,8659,dArr,8660,hArr,8756,there4,8834,sub,8835,sup,8836,nsub,8838,sube,8839,supe,8853,oplus,8855,otimes,8869,perp,8901,sdot,8968,lceil,8969,rceil,8970,lfloor,8971,rfloor,9001,lang,9002,rang,9674,loz,9824,spades,9827,clubs,9829,hearts,9830,diams,8194,ensp,8195,emsp,8201,thinsp,8204,zwnj,8205,zwj,8206,lrm,8207,rlm,173,shy,233,eacute,237,iacute,243,oacute,250,uacute,193,Aacute,225,aacute,201,Eacute,205,Iacute,211,Oacute,218,Uacute,221,Yacute,253,yacute”,
    plugins : “spellchecker,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,flash,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable”,
    theme_advanced_buttons1_add : “fontselect,fontsizeselect”,
    theme_advanced_buttons2_add : “preview,fullscreen,separator,forecolor,backcolor”,
    theme_advanced_buttons2_add_before: “cut,copy,paste,pastetext,pasteword,separator,search,replace,separator”,
    theme_advanced_buttons3_add_before : “tablecontrols,separator”,
    theme_advanced_buttons3_add : “emotions,iespell,flash,advhr,separator,ltr,rtl,separator,spellchecker”,
    theme_advanced_toolbar_location : “top”,
    theme_advanced_toolbar_align : “left”,
    theme_advanced_path_location : “bottom”,
    content_css : “”,
    extended_valid_elements : “hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]“,
    file_browser_callback : “avsOpenFileBrowser”,
    theme_advanced_resize_horizontal : false,
    theme_advanced_resizing : true,
    apply_source_formatting : true,
    spellchecker_languages : “+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv”,
    width: “100%”, height: “400″,
    relative_urls : false,
    convert_urls : false,
    convert_fonts_to_spans : true,
    elements : “edittorId”,
    theme_advanced_path : false,
    setup : function(ed) {
    ed.onKeyUp.add(function(ed, e) {
    var txt = “test”;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id+’_path_row’), txt);
    });
    }
    });

  12. Irn says:

    New to TinyMCE but shouldn’t the reference to “tinyMCE.activeEditor.”
    be the variable “ed”? This will stop issues with multiple text areas.

  13. broof says:

    Hi,
    I wrote a custom button for tinyMCe that searches the document inside the editor for a blank (‘______’). If it finds a blank it highlights it. It keeps track of where it is in the document so the next click of the button will find the next blank. When it reaches the end, it resets the counter so the next call will start at the top and find the first blank.

    What I want to be able to do is when the page first loads, call the button click programmatically (maybe with javascript function) so the first blank will be highlighted.

    I tried this code:tinyMCE.activeEditor.execCommand(‘mybutton’); but it doesn’t work. I’m not sure where this function would go or how to call it. Can you help?

  14. Mangal says:

    Thanks for posting. It works pretty well. I have done some enhancement like.

    1. Setting different character limit for different textareas on the basis of ids.

    2. Maintain the previous formatting

    The modified script are following>>>>

    var characterLimit;

    tinyMCE.init({
    mode : “textareas”,
    theme : “advanced”,
    plugins : “paste”,
    theme_advanced_buttons1 : “bold,italic,underline,separator,cut,copy,pastetext,selectall,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,undo,redo,separator,blockquote,sub,sup,separator,charmap,code”,
    theme_advanced_buttons2 : “”,
    theme_advanced_buttons3 : “”,
    theme_advanced_toolbar_location : “top”,
    theme_advanced_toolbar_align : “left”,
    apply_source_formatting : true,
    paste_auto_cleanup_on_paste: true,
    paste_retain_style_properties: false,
    paste_strip_class_attributes: true,
    paste_remove_spans: true,
    paste_remove_styles: true,
    paste_remove_styles_if_webkit: true,
    cleanup: true,
    theme_advanced_statusbar_location : “bottom”,
    /**Stop paste (ctrl+v) directly on tinymce**/
    /*setup : function(ed) { ed.onPaste.add( function(ed, e, o) {
    return tinymce.dom.Event.cancel(e);
    } );
    } */

    setup :function(ed) {

    ed.onPaste.add( function(ed, e, o) { return tinymce.dom.Event.cancel(e); });
    ed.onBeforeSetContent.add(function(ed, o) {
    characterLimit = getCharacterLimt(tinyMCE.activeEditor.id);
    var strip = (tinyMCE.activeEditor.getContent()).replace(/(]+)>)/ig,”");
    var text = strip.split(”).length + ” Words, ” + strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” characters remaining. “;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    }
    );

    ed.onKeyUp.add(function(ed, e) {
    characterLimit = getCharacterLimt(tinyMCE.activeEditor.id);
    var strip = (tinyMCE.activeEditor.getContent()).replace(/(]+)>)/ig,”");
    var text = strip.split(‘ ‘).length + ” Words, ” + strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” characters remaining. “;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    if(strip.length > characterLimit){
    strip = s(tinyMCE.activeEditor.getContent()).substring(0,characterLimit);
    tinyMCE.execCommand(‘mceSetContent’,false,strip);
    var text = “The length of your content is “+strip.length +”. Maximum characters allowed for this text area is “+characterLimit+”. “;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    }
    });

    ed.onChange.add(function(ed, e) {
    characterLimit = getCharacterLimt(tinyMCE.activeEditor.id);
    var strip = (tinyMCE.activeEditor.getContent()).replace(/(]+)>)/ig,”");
    var text = strip.split(‘ ‘).length + ” Words, ” + strip.length + ” Characters. You have ” +(characterLimit-strip.length)+” characters remaining. “;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    if(strip.length > characterLimit){
    strip = (tinyMCE.activeEditor.getContent()).substring(0,characterLimit);
    tinyMCE.execCommand(‘mceSetContent’,false,strip);
    var text = “The length of your content is “+strip.length +”. Maximum characters allowed for this text area is “+characterLimit+”. “;
    tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + ‘_path_row’), text);
    }
    });

    }

    });

    function getCharacterLimt(id)
    {
    var lmt = 1000;
    if (id == ‘id1′ || id == ‘id2′)
    {
    lmt = 2000;
    }else if (id == ‘id3′ || id == ‘id4′)
    {
    lmt = 4000;
    }else
    {
    lmt = 1000;
    }

    return lmt;
    }

  15. Mangal says:

    One more enhancement i did to disable paste (ctr+v and right menu paste)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.