5

I'm working on a simple note taking application and using GhostDown Markdown editor. It's pretty nice, I like it, but I am stuck trying to set it's value programatically.

I can get values out pretty easily. $('.entry-markdown-content textarea').val()

Setting it however is another story... :(

Prototype of what I'm working on can be seen at http://potusnotes.com

Serhiy
  • 2,505
  • 3
  • 33
  • 49
  • you are on this [Ghost-Markdown-Editor](https://github.com/timsayshey/Ghost-Markdown-Editor) version ? – Blag Nov 17 '15 at 23:02
  • @Blag not sure, but if you provide the answer for the latest version, I will be sure to update if necessary – Serhiy Nov 17 '15 at 23:25
  • it was more about the fork than the version (As I don't find an official site for GhostDown Markdown editor ); I've take a look on the source code, but it's a bit messy <_> ; it seem to have `getMarkdown` and `getHtml`, but no setter... ; and as they use an overlay, if you don't find the right method, it's pointless – Blag Nov 17 '15 at 23:33

1 Answers1

3

For the editor part, Ghost-Markdown-Editor uses CodeMirror editor. So, to set value programmatically, we would call CodeMirror's instance and do

editor.setValue(txt);

But how to get that CM instance? It was created by the widget with which Ghost-Markdown-Editor was created. See jquery.ghostdown.js file:

$.widget( "b4m.ghostDown", {
    editor: null,
    // ...
    _create: function() {
        // ...
        this.editor = CodeMirror.fromTextArea(this.element.find('textarea')[0], {
            mode: 'markdown',
            tabMode: 'indent',
            lineWrapping: true
        });
    }

}

As the widget was made with jQuery Widget factory, a widget instance is kept inside .data("plugin-name") element of the object it was used on.

Thus we can access widget instance and set editor value like this:

var ghostdown = $(".editor").data("b4m-ghostDown");
ghostdown.editor.setValue("# Hello, SO");

Or simply

$(".editor").data("b4m-ghostDown").editor.setValue("# Hello, SO");
Vaviloff
  • 16,282
  • 6
  • 48
  • 56
  • 1
    Great, thank you much, this exactly what I was looking for. I thought it would be something like that but had trouble figuring it out myself. – Serhiy Nov 18 '15 at 12:18
  • Glad I could help! Luckily it was CodeMirror under the hood. – Vaviloff Nov 18 '15 at 13:43