Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get CodeMirror instance

I want to get an instance of CodeMirror (it is binded to a textarea '#code'). From an onclick-event I want to add a value to the current value of the CodeMirror instance. How can this be achieved? From the docs I can't seem to find anything to get an instance and bind it to a loca var in javascript.

like image 962
Ben Fransen Avatar asked Jul 20 '12 14:07

Ben Fransen


People also ask

How do I use CodeMirror?

Once you import CodeMirror via <script> tag, you get a CodeMirror global that you can use to create a new CodeMirror instance. Just point it at a <div> and CodeMirror does the rest. CodeMirror(document. querySelector('#my-div'), { lineNumbers: true, tabSize: 2, value: 'console.

What is CodeMirror CSS?

CodeMirror is a code editor component for the web. It can be used in websites to implement a text input field with support for many editing features, and has a rich programming interface to allow further extension.

How do I reset CodeMirror editor?

If you don't want to kill the CodeMirror instance, just change the entire document holding the text, data on markers etc. This can be done by calling cm. swapDoc(doc: CodeMirror. Doc) .


2 Answers

Another method I have found elsewhere is as follows:

//Get a reference to the CodeMirror editor var editor = document.querySelector('.CodeMirror').CodeMirror; 

This works well when you are creating the CodeMirror instance dynamically or replacing an existing DOM element with a CodeMirror instance.

like image 57
ashatte Avatar answered Sep 22 '22 11:09

ashatte


Someone just posted an answer but removed it. Nevertheless, it was a working solution. Thanks!

-- Basically this was his solution:

// create an instance var editor = CodeMirror.fromTextArea('code'); // store it $('#code').data('CodeMirrorInstance', editor); // get it var myInstance = $('code').data('CodeMirrorInstance'); // from here on the API functions are available to 'myInstance' again. 
like image 28
Ben Fransen Avatar answered Sep 22 '22 11:09

Ben Fransen