How to call javascript function in TinyMCE? - javascript

My application can edit certain word but not all, using contenteditable HTML attribute I can do that. Now The problem is I want to move <?php echo $konten;?> inside textarea with id post_content witch is make textarea become TinyMCE text editor. But my javascript function become not working. I already using init_instance_callback but it still not work. This is my code :
<style>
*[contenteditable="true"] {
background-color: rgba(217, 245, 255,0.5);
}
</style>
<?php
// $konten = $template['konten'];
$konten = "<p>Hai this is the content.</br> My name is : {{name}}</br></p><p></br><table border ='1'><tr><td>This is table</td></tr><tr><td>{{loop_table_one}}</td></tr></table></br><ol><li>{{loop_list_one}}</li></ol></p>";
preg_match_all('/{{(.*?)}}/', $konten, $variable);
$a = array_unique($variable[0]);
foreach($a as $item) {
$b = preg_replace('/{{(.*?)}}/is', "$1", $item);
if (strtolower(substr($b, 0, 9)) == 'loop_list') {
$konten = str_ireplace($item, '<span class="input-list input-'.$b.'" name="'.$b.'">'.$item.'</span>', $konten);
} else if (strtolower(substr($b, 0, 10)) == 'loop_table') {
$konten = str_ireplace($item, '<span class="input-table input-'.$b.'" name="'.$b.'">'.$item.'</span>', $konten);
} else {
$konten = str_ireplace($item, '<span class="input-variable input-'.$b.'" name="'.$b.'" contentEditable="true">'.$item.'</span>', $konten);
}
}
?>
<textarea id="post_content">
<?php echo $konten;?>
</textarea>
<script>
$(document).ready(function(){
$(".input-variable").on('DOMSubtreeModified',function(e){
e.stopPropagation();
let cls = $(this).prop('class');
// remove string inputt
let id = cls.replace("input-variable ", "");
let val = $(this).html();
$('.'+id).each(function () {
if ($(this).html() != val) {
$(this).html(val);
}
})
e.stopPropagation();
});
$( ".input-list" ).closest('ol').add($( ".input-list" ).closest('ul')).prop("contentEditable", "true");
$( ".input-table" ).closest('table').prop("contentEditable", "true");
});
function myCustomInitInstance(inst) {
// i already move my function here but still now working
}
tinymce.init({
init_instance_callback : "myCustomInitInstance",
table_class_list: [
{title: 'None', value: ''},
{title: 'Editable Table', value: 'editablecontent'}
],
readonly:1,
content_style: "body { font-family: Cambria; }",
selector: "#post_content",
toolbar: '#mytoolbar',
lineheight_formats: "8pt 9pt 10pt 11pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 36pt",
// ukuran A4 Potrait
width : "742",
height : "842",
plugins: 'textcolor table paste',
font_formats:
"Cambria=cambria;Calibri=calibri;Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Oswald=oswald; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats",
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern"
],
style_formats: [
{
title: 'Line height',
items: [
{
title: 'Default',
inline: 'span',
styles: { 'line-height': 'normal', display: 'inline-block' }
},
{
title: '1',
inline: 'span',
styles: {'line-height': '1', display: 'inline-block'}
},
{
title: '1.1',
inline: 'span',
styles: {'line-height': '1.1', display: 'inline-block'}
},
{
title: '1.2',
inline: 'span',
styles: {'line-height': '1.2', display: 'inline-block'}
},
{
title: '1.3',
inline: 'span',
styles: {'line-height': '1.3', display: 'inline-block'}
},
{
title: '1.4',
inline: 'span',
styles: {'line-height': '1.4', display: 'inline-block'}
},
{
title: '1.5',
inline: 'span',
styles: {'line-height': '1.5', display: 'inline-block'}
},
{
title: '2 (Double)',
inline: 'span',
styles: {'line-height': '2', display: 'inline-block'}
}
]
},
{title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
],
toolbar: "insertfile undo redo | styleselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image responsivefilemanager | formatselect | strikethrough | forecolor backcolor fontselect fontsizeselect | pastetext |",
convert_fonts_to_spans: true,
paste_word_valid_elements: "b,strong,i,em,h1,h2,u,p,ol,ul,li,a[href],span,color,font-size,font-color,font-family,mark,table,tr,td",
paste_retain_style_properties: "all",
automatic_uploads: true,
image_advtab: true,
images_upload_url: "<?php echo base_url("template/tinymce_upload")?>",
file_picker_types: 'image',
paste_data_images:true,
relative_urls: false,
remove_script_host: false,
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
var id = 'post-image-' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var blobInfo = blobCache.create(id, file, reader.result);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
};
input.click();
}
});
</script>

If you are trying to use init_instance_callback you have to pass it a function. In your code example you have:
init_instance_callback : "myCustomInitInstance",
...so you are passing a string to a configuration option that expects a function. Here is a TinyMCE Fiddle that shows how to pass a function to the init_instance_callback configuration option:
https://fiddle.tiny.cloud/18haab

Related

How to change value in attribute title for button on the toolbar tinymce?

I need for the element "Supersctipt" set attribute title value as "footnote".
By default here "Superscript".
I don't know a way how to do it. Here is my code tinymce:
initTinyMCE()
function initTinyMCE(selector = '.js-tinymce') {
tinymce.init({
selector: selector,
skin: false,
branding: false,
menubar: false,
height: 500,
toolbar:
'undo redo | formatselect | bold italic underline superscript | bullist numlist | removeformat code',
plugins: [
"code", "paste", "lists"
],
paste_as_text: true,
block_formats: 'Paragraph=p; Header 3=h3; Header 4=h4; Header 5=h5; Header Underline=h6; ',
content_css: '/css/tinymce.css?' + new Date().getTime(),
})
}
I tried through jQuery refer to this element, but without success, because tinymce inits a little later:
$(function() {
$('.js-tinymce button[title="Superscript"]').attr('aria-label', 'footnote')
})
I also tried this way, reading documentation:
formats: {
sup: { selector: 'sup'},
},
style_formats: [
{ title: 'footnote', format: 'sup' },
]
But without success too( Finally, how to do this easy task?
Yeeeah! I've solved the problem by adding setup:... option to the end of tinymce init object. Code:
initTinyMCE()
function initTinyMCE(selector = '.js-tinymce') {
tinymce.init({
selector: selector,
skin: false,
branding: false,
menubar: false,
height: 500,
toolbar:
'undo redo | formatselect | bold italic underline superscript | bullist numlist | removeformat code',
plugins: [
"code", "paste", "lists"
],
paste_as_text: true,
block_formats: 'Paragraph=p; Header 3=h3; Header 4=h4; Header 5=h5; Header Underline=h6',
content_css: '/css/tinymce.css?' + new Date().getTime(),
setup: function(tinyMCE) {
tinyMCE.on('init', function() {
$('[aria-label="Superscript"]').attr('title', 'Footnote')
});
},
})
}

Add alert to TinyMCE textbox

I'm trying to add alert box to my textbox area so I can not add any alert box that will appear on the page's content.
How will I only add it?
I have tried to do this:
importcss_groups: [
{ text: 'Succes (Green)', value: 'alert alert-success' },
{ text: 'Info (Blue)', value: 'alert alert-info' }
]
i have try to make its here:
It must be such that it makes them bootstrap alert.
My TinyMCE code:
tinymce.init({
selector: 'textarea',
theme: 'modern',
height: 350,
plugins: [
'advlist autolink image link lists charmap anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'save table contextmenu directionality emoticons paste textcolor bbcode'
],
content_css: [
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css',
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css'
],
importcss_groups: [
{ text: 'Succes (Green)', value: 'alert alert-success' },
{ text: 'Info (Blue)', value: 'alert alert-info' }
]
});
I have complete its now:
i have add
style_formats: [{
title: 'Succes (Grøn)',
block: 'div',
classes: 'alert alert-success'
}, {
title: 'Info (Blå)',
block: 'div',
classes: 'alert alert-info'
}, {
title: 'Warning (Gul)',
block: 'div',
classes: 'alert alert-warning'
}, {
title: 'Danger (Rød)',
block: 'div',
classes: 'alert alert-danger'
}]

TinyMCE focus in and focus out loop

I have a problem with TinyMCE 4.x and its behavior. Whenever I initialize TinyMCE on popup i get focus in and focus out loop and its looks like flickering.
Here is a gif that shows exactly what is happening. You can see that on main page where i initialize TinyMCE everything is fine and its working as expected, but on popup its kinda start focusing in and out. You can see it in developer tool as well, that class for it changes from mce-content-body to mce-content-body mce-edit-focus and then back.
Here is code how I initialize the TinyMCE.:
initializeTinyMCE(element){
var self = this;
if (element == 'p') {
var toolbar = 'forecolor | fontsizeselect fontselect | align | bold italic underline | bullist numlist | link | strokes | done';
} else if (element == 'h') {
var toolbar = 'forecolor | fontsizeselect | fontselect | H | align | bold italic underline | link | strokes | done';
}
if(self.el.parent().hasClass('popup_content')){
var inline = false
} else {
var inline = true
}
tinyMCE.init({
selector: `#${self.el.find('.content_element').attr('id')}`,
auto_focus: self.testFocus(self.el.find('.content_element').attr('id')),
content_css : 'assets/tinymce/custom/fonts.css',
inline: true,
menubar: false,
theme: 'modern',
skin: 'pagesource',
plugins: ['lists link textcolor colorpicker strokes'],
toolbar: toolbar,
fontsize_formats: '8px 10px 12px 14px 18px 24px 36px 48px',
setup: function (editor) {
self.clonedEl = self.el.clone()
editor.addButton('align', {
type: 'menubutton',
text: '',
icon: 'alignleft',
menu: [{
text: '',
icon: 'alignleft',
onclick: function () {
editor.execCommand('JustifyLeft');
}
}, {
text: '',
icon: 'aligncenter',
onclick: function () {
editor.execCommand('JustifyCenter');
}
}, {
text: '',
icon: 'alignright',
onclick: function () {
editor.execCommand('JustifyRight');
}
}, {
text: '',
icon: 'alignjustify',
onclick: function () {
editor.execCommand('JustifyFull');
}
}]
}),
editor.addButton('H', {
type: 'menubutton',
text: 'H',
icon: false,
menu: [{
text: 'H1',
onclick: function() {
editor.execCommand('FormatBlock', false, 'h1');
}
}, {
text: 'H2',
onclick: function() {
editor.execCommand('FormatBlock', false, 'h2');
}
}, {
text: 'H3',
onclick: function() {
editor.execCommand('FormatBlock', false, 'h3');
}
}, {
text: 'H4',
onclick: function() {
editor.execCommand('FormatBlock', false, 'h4');
}
}, {
text: 'H5',
onclick: function() {
editor.execCommand('FormatBlock', false, 'h5');
}
}, {
text: 'H6',
onclick: function() {
editor.execCommand('FormatBlock', false, 'h6');
}
}]
});
editor.addButton('done', {
text: 'Done',
icon: false,
onclick: function () {
tinyMCE.remove();
self.openEditManager();
self.el.find('.ui-resizable-handle').removeClass('hidden');
}
});
editor.on('remove', function(ed) {
self.removeTinyMCE(ed);
window.historyMem.addRecord(self.clonedEl, self.el.clone())
});
},
init_instance_callback: function (editor) {
editor.on('focus', function (e) {
console.log(2)
});
}
});
}
And this is the element and structure on which the problem persists:
<div class="body_wrapper">
<div class="project_wrapper" data-uuid="<%= #page.uuid %>">
<div class="edit_grid">
<div class="popup_editor">
<div class="popup">
<div class="popup_content">
<div class='widget'>
<div class='tinymce_editor'> # this is the element
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Note: When not doing inline editor it works fine.
I don't need exact solution, any suggestions and ideas would be appreciated. I have tried almost everything, like moving editor popup in different position in DOM, stripping all of the settings, etc. Thank you.

how to use TinyMCE visual_anchor_class

Using TinyMCE, I want to be able to add a custom class to some of the anchor tags in my editor. I found visual_anchor_class which I can't get to work. I've created a class called .anchorBtn and added contextmenu to my init.
When I right-click over my anchor (where it says "DONATE"), I see an empty white box.
tinymce.init({
selector: selector,
menubar: false,
height: 300,
plugins: [
"link anchor lists code paste image contextmenu"
],
statusbar: false,
toolbar: 'undo redo | bold italic underline | bullist numlist | buttons link image | code',
content_css : "css/tinyMCE.css",
link_list:"cgi/linkList.exe?token="+tkn,
force_br_newlines : false,
force_p_newlines : false,
forced_root_block : '',
body_class: "mceBackColor",
oninit : "setPlainText("+selector+")",
visual_anchor_class: 'anchorBtn',
contextmenu: "anchorBtn",
paste_as_text: true,
file_browser_callback: function(field_name, url, type, win) {
var tkn=getToken();
$("#PDFuform").attr("action", "cgi/pdfUpload.exe");
$("#pdfToken").val(tkn);
$("#pdfField").val(field_name);
$('#PDFuform input').click();
},
setup: function (editor) {
editor.addButton('buttons', {
type: 'menubutton',
text: 'Custom Buttons',
icon: false,
menu: [
{
image : '../img/tourBtn.jpg',
title : "SCHEDULE A TOUR",
text: "SCHEDULE A TOUR",
icon: false,
onclick: function () {
editor.insertContent("<div class='bbtn bSAT'>SCHEDULE A TOUR</div>");
}
}
]
})
}
});
What am I doing wrong?

Is it a bug to validate dynamic TinyMCE with bootstrap validator or something wrong with my code?

All
I'm using Bootstrap Validator now. But I have a problem to validate dynamic TinyMCE.
If only 1 TinyMCE, it works.
But if I have more than 1 TinyMCE all of my TinyMCE will get same error although it's only 1 of my TinyMCE doesnt meet the requirement, all of my TinyMCE that already meet the requirement will get same error too.
But if I'm not using TinyMCE on my textarea, it works. I think there's a problem with multiple TinyMCE with same name.
I dont know what's wrong. Already see the example to validate multiple name and tinymce from Bootstrap Validator, but cant solve this problem.
My code exactly same with the example, the different only I added TinyMCE on my textarea.
http://bootstrapvalidator.com/examples/adding-dynamic-field/
http://bootstrapvalidator.com/examples/tinymce/
This is my code
<div class="panel-body hide" id="formUser">
<div class='form-group'>
<label class='control-label'>Name</label>
<input type='text' class='form-control' placeholder='Enter Name' name='Name[]' >
</div>
<div class='form-group'>
<label class='control-label'>Hobbies</label>
<textarea class='form-control' name='Hobbies[]' ></textarea>
</div>
</div>
This is the code to add dynamic TinyMCE and validate it
function initTinyMCE(){
tinymce.init({
forced_root_block : "",
force_br_newlines : true,
force_p_newlines : false,
selector: "textarea#desc"+i,
theme: "modern",
width: 1287,
height: 400,
relative_urls : false,
remove_script_host: false,
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
"searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
"save table contextmenu directionality emoticons template paste textcolor jbimages"
],
toolbar: "insertfile undo redo | styleselect | bold italic | fontselect | fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image jbimages | print preview media fullpage | forecolor backcolor emoticons",
style_formats: [
{title: 'Bold text', inline: 'b'},
{title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
{title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
{title: 'Example 1', inline: 'span', classes: 'example1'},
{title: 'Example 2', inline: 'span', classes: 'example2'},
{title: 'Table styles'},
{title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
],
setup: function(editor) {
editor.on('keyup', function(e) {
// Revalidate the hobbies field
$('.formUser').bootstrapValidator('revalidateField', 'Hobbies[]');
});
}
});
}
$(document).ready(function() {
//initTinyMCE();
.bootstrapValidator({
excluded: [':disabled'],
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'Name[]': {
message: 'The nameis not valid',
validators: {
notEmpty: {
message: 'The nameis required and cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The title must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_ ]+$/,
message: 'The name can only consist of alphabetical, number and underscore'
}
}
},
'Hobbies[]': {
validators: {
callback: {
message: 'The hobbies must be between 5 and 200 characters long',
callback: function(value, validator, $field) {
// Get the plain text without HTML
var text = tinyMCE.activeEditor.getContent({
format: 'text'
});
return text.length <= 200 && text.length >= 5;
}
},
}
},
}
})
.on('click','.addUser', function() {
var $template = $('#formUser'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.insertBefore($template),
$option1 = $clone.find('[name="Name[]"]');
$option2 = $clone.find('[name="Hobbies[]"]');
$clone.find(".wrap").attr("id","wrap"+i);
$clone.find("textarea").attr("id","desc"+i);
$clone.find("textarea").attr("class","form-control desc"+i);
$clone.find('.wrapper').attr('id','wrapper'+i);
$clone.find('button').attr('onclick','deleteForm(\'wrapper'+i+'\')');
initTinyMCE();
// Add new field
$('.formUser').bootstrapValidator('addField',$option1);
$('.formUser').bootstrapValidator('addField',$option2);
i++;
})
});
Waiting for your help guys.
Really appreciate for your help guys.
Thank You
Try this
Html
<form id="tinyMCEForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-md-3 control-label">Hobbies</label>
<div class="col-md-9">
<textarea class="form-control" name="hobbies" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-5 col-md-offset-3">
<button type="submit" name="myBtn" class="btn btn-default">Validate</button>
</div>
</div>
</form>
Javascript
$(document).ready(function () {
tinymce.init({
selector: 'textarea',
setup: function (editor) {
editor.on('keyup', function (e) {
console.debug('Editor contents was modified. Contents: ' + editor.getContent({
format: 'text'
}));
$('#tinyMCEForm').bootstrapValidator('revalidateField', 'hobbies');
});
}
});
$('#tinyMCEForm')
.bootstrapValidator({
excluded: [':disabled'],
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
hobbies: {
validators: {
callback: {
message: 'The hobbies must be between 5 and 200 characters long',
callback: function (value, validator, $field) {
// Get the plain text without HTML
var text = tinyMCE.activeEditor.getContent({
format: 'text'
});
return text.length <= 200 && text.length >= 5;
}
}
}
}
}
})
.on('success.form.bv', function (e) {
e.preventDefault();
});
});

Categories

Resources