Search code examples
javascripthtmltinymcejinja2

tinymce wont init in function, works in browser console


I have a function which appends HTML to a div and then tries to initialize tinyMCE on the <textarea> fields:

function refreshNotes() {
            {#console.log("fetching notes")#}
            $.get({
                url: "/notes/{{ record_id }}",
                dataType: "json"
            }, (response) => {
                $("#noteCollapseNotes").empty()
                const notes = Object.entries(response["data"])
                {#console.log(notes)#}
                
                for (const [key, note] of notes) {
                    {#console.log(key, note)#}
                    $("#noteCollapseNotes").append(getNoteHTML(key, note))
                    
            })
            tinymce.init({
                selector: ".readonly",
                readonly: true,
                menubar: false,
                toolbar: false,
                height: 100
            });
        }

refreshNotes is called whenever a user performs a CRUD action on a note. getNoteHTML() produces a <div> with a <textarea> inside that contains the .readonly class

the tinymce.init call at the end of refreshNotes() does not work for some reason.

However if I go into the console and paste the same call, the editors initialize successfully. What is the issue here?


Solution

  • Most likely you have a timing issue in your JavaScript. You have a $.get() call that looks to be asynchronous and then immediately after that you have an attempt to init TinyMCE. You are not making your DOM nodes until after that asynchronous call returns but you are initializing TinyMCE right after you start your call to get data from the server. When you try to call things from the console the $.get() is likely done and things work as you want them to.

    I would move the tinymce.init({}) call inside your success function after the completion of the for look that creates the new DOM nodes.