Search code examples
javascriptdynamictinymcekeyuponkeyup

Populate a div from TinyMCE content dynamically


I'm trying to get the contents from a TinyMCE textarea to populate a button/div as I type. This is to show the client how the button/div will look like when it goes live. Everything else works dynamically, such as the button/div colour, the title and dropdown.

The issue lies with dynamically retrieving the contents from TinyMCE. If I use a standard textarea box it works fine. I want the client to be able to use some of the basic features of TinyMCE.

Kind of how this form field is working. As I'm typing in this box, I can see my text updating below.

My JS is:

$(document).on('change', '#ParentID', function() {
    var NTxt = $('#ParentID option:selected').text();
    var NVal = document.getElementById("ParentID").value;
    NTxt = NTxt.replace(/ @ /g,"<br/>");
    if(NVal != "0"){
        if(NTxt.value != null || NTxt.value != "0" || NTxt.value != undefined){
        $("#LTxt").html(NTxt);
        }
    }else{
        $("#LTxt").html('External Link Text/Quote Text');
    }
});
$(document).on('keyup', '#Opt2', function() {
   $('#LTxt').text($(this).val());
});

Here are some screen grabs:

1. Normal State:

enter image description here 2. Populated title and dropdown "internal link" text:

enter image description here 3. Textarea, populating same place (WITHOUT TINYMCE):

enter image description here Anyone know how I can do this with TinyMCE? I've tried...

tinymce.get('content id').getContent()

...but it didn't seem to populate dynamically.

This is the key question: How to pass anything typed into the TinyMCE textarea into the button, at the bottom, as the user is typing?

Many thanks in advance,

Glynn


Solution

  • You need to use a variety of events that TinyMCE triggers to know when its content has changed. You can then grab the content from the editor and do whatever you need with it.

    Here is an example that shows the actual raw HTML in a neighboring DIV. It can easily be adapted to insert the HTML into an elements so its actually rendered to the page.

    http://fiddle.tinymce.com/Gegaab/5

    The list of available events is documented here: https://www.tinymce.com/docs/advanced/events/#editorevents

    The example uses the keydown and change events in particular but there are many to choose from if those don't fit your needs.