Search code examples
javascripttinymce

How to call javascript function in TinyMCE?


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>

Solution

  • 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