Search code examples
javascripthtmltinymcegetuikit

tinyMCE 5 with getUIKIT uk-accordion (hide/show div)


I am using tinyMCE 5, and getUIKIT 3. I put the editor inside a uk-accordion, which allows me to show/hide the div. All goes well the first time I show the div, the editor is there fully functioning. I hide the div, show again - sometimes the editor is there sometimes not. From then on, it is never there when I hide/show. Here s a codepen with the problem: https://codepen.io/prtome/pen/gJLdKo?editors=1111

and my code (very simple): HTML

<ul uk-accordion>
  <li  id="toto">
    <a class="uk-text-primary uk-accordion-title" href="#">Item toto</a>
    <div class="uk-accordion-content">
        <textarea id="basic-example"></textarea>

     </div>
   </li>
 </ul>

AND JS code:

UIkit.util.on('#toto', 'shown', function (event) {
 tinymce.EditorManager.execCommand('mceAddEditor',false, 'basic-example');
  $('#basic-example').html("<p style=\"text-align: center;\"> blabla bla bla bla bla I can edit this </p>");
  tinymce.init({
  selector: 'textarea#basic-example',
  height: 200,
  menubar: true,
  plugins: [
    'advlist autolink lists link image charmap print preview anchor ',
    'searchreplace visualblocks code fullscreen',
    'insertdatetime media table paste code help wordcount'
  ],
  toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
  content_css: [
    '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
    '//www.tiny.cloud/css/codepen.min.css'
  ]
 });
});

UIkit.util.on('#toto', 'hidden', function (event) {
 tinymce.execCommand('mceRemoveEditor', false, "basic-example");      
})

I have no errors in the console. I cannot find what it is that I am doing wrong - but it is obvious something is not working as it should. If anybody could point where the problem is it will be very helpful. Thanks


Solution

  • This is likely due to how UIKIT handles showing and hiding things. If it uses display:none to "hide" elements when not visible and changes the visibility when the items are to be shown - this will cause issues for TinyMCE because when the element has display:none it is no longer part of the DOM. When you later show the contents of the accordion the display:none is changed to display:block and the elements are now part of the DOM. Effectively each time you show/hide something you are likely creating and destroying DOM elements.

    What you need to do is not init() TinyMCE until the <textarea> is shown via the action that "shows" the appropriate <textarea>. When you hide that accordion you need to use the remove() API to disconnect TinyMCE before the accordion close happens (e.g. before the <li> reverts to display:none and the elements are removed from the DOM).

    I don't know if you can force UIKIT to use visibility:hidden as opposed to display:none but that would eliminate all of this if that is possible.