Benjamin W Benjamin W - 10 days ago 6
Javascript Question

Javascript medium-editor markdown append image and update content

<div class="editable" contenteditable="true"></div>
<textarea name="markdown" class="markdown" /></textarea>//display none

new MediumEditor('.editable', {
extensions: {
markdown: new MeMarkdown(function (md) {
document.querySelector(".markdown").textContent = md;
}),
img: new imgButton()
}


$('.editable').append("<img src='abc' />");


I have a div use medium-editor & medium-editor markdown

when user type inside of
.editable
,
textarea
will sync.

I also have a button click, it will append an image into
.editable


my problem is markdown only update when
.editable keypress


so if I append text,
textarea
wont sync, unless I press any key inside of
.editable
again

anyone know how to tell markdown to update after append image

Answer

try this

function updateTextArea(index,editable){
    var textarea = editable.parentNode.querySelector('textarea[medium-editor-textarea-id="' + editable.getAttribute('medium-editor-textarea-id') + '"]');
    if (textarea) {
        textarea.value = editable.innerHTML.trim();
    }
}

$('.editable').append("<img src='abc' />");
$('.editable').each(updateTextArea);

The updateTextArea function will update a text area corresponds to editable area.

Here is the code I tried

var editor = new MediumEditor('.editable', {
            buttonLabels: 'fontawesome'
        });
           function updateTextArea(index,editable){
                var textarea = editable.parentNode.querySelector('textarea[medium-editor-textarea-id="' + editable.getAttribute('medium-editor-textarea-id') + '"]');
                if (textarea) {
                    textarea.value = editable.innerHTML.trim();
                }
            }
    $("#addImage").click(function(){
      $('.editable').append("<img src='abc' />");
      $('.editable').each(updateTextArea);
     });
$('.editable').change(updateTextArea);
<link href="http://yabwe.github.io/medium-editor/bower_components/medium-editor/dist/css/themes/tim.min.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css" rel="stylesheet"/>
<link href="http://yabwe.github.io/medium-editor/bower_components/medium-editor/dist/css/medium-editor.min.css" rel="stylesheet"/>
<script src="http://yabwe.github.io/medium-editor/bower_components/medium-editor/dist/js/medium-editor.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="container">
        <h1>Medium Editor</h1>
        <textarea class="editable medium-editor-textarea" name="markdown" id="markdown">&lt;p&gt;Textarea is now supported&lt;/p&gt;</textarea>
        <input type="button" id="addImage" value="Add Image">
       <input type="button" value="Alert textarea content" onclick="alert(document.getElementById('markdown').value)">
    </div>