Skip to content

Instantly share code, notes, and snippets.

@1naveengiri
Created March 14, 2018 11:40
Show Gist options
  • Select an option

  • Save 1naveengiri/a42a816db255eb654cb208c58b71d4df to your computer and use it in GitHub Desktop.

Select an option

Save 1naveengiri/a42a816db255eb654cb208c58b71d4df to your computer and use it in GitHub Desktop.
Set Character limit for tinymce Text Editor
/**
* This was an expamle of tinymce in repeatable field
* I hav't handled case for copy paste text in the editor so max limit will not be checked when you cntl+c&cntl+v
* but on texteditor change I have reset the content to max char limit.
*/
jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {
jQuery(".games-section .repeatable-item").each(function(){
var this_id = jQuery(this).attr('data-items');
var this_id = 'book_game_item_description_' + this_id;
// on keypress check the char limit, It will take space as char and not allow to write after char limit crossed.
tinyMCE.get(this_id).on( 'keypress', function(e) {
var body = tinymce.get(this_id).getBody();
var content = tinymce.trim(body.innerText || body.textContent);
var max = 230;
var len = content.length;
var diff = max - len;
if ( diff < 1 )
tinymce.dom.Event.cancel(e);
});
// on tinymce change event fire, It will check if anything other texteditor have limit crossed text then reset it to max limit.
tinyMCE.get(this_id).on( 'change', function(e) {
jQuery(".games-section .repeatable-item").each(function(){
var game_editor_id = jQuery(this).attr('data-items');
var game_editor_id = 'book_game_item_description_' + game_editor_id;
var body = tinymce.get(game_editor_id).getBody();
var content = tinymce.trim(body.innerText || body.textContent);
var max = 230;
var len = content.length;
var diff = max - len;
if ( diff < 1 )
content = content.substring(0,230);
tinyMCE.get(game_editor_id).setContent(content);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment