Friday, December 30, 2016

TinyMCE Get Word Counts Using jQuery

Sample code snippet (Full TinyMCE Example)

var log = $(".log"), previous_content = "";
var plugins = [
    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker textpattern"
];
tinymce.init({
    selector: ".rich_editor",
    setup: function (editor) {
        editor.on('change redo undo', function () {
            editor.save();
            var body = tinymce.activeEditor.getBody();
            var content = tinymce.trim(body.innerText || body.textContent);
            if(content != previous_content) {
                content = $.trim(content.replace( /[^\w ]/g, " "));
                var word_count = content == "" ? 0 : content.split( /\s+/ ).length;
                log.prepend("Word_Count=" + word_count + "<br/>");
                log.prepend("Editor_Text=" + content + "<br/>");
                previous_content = content;
            }
        });
    }
});

Sample output


No comments:

Post a Comment