Search code examples
javascriptcodemirror

Change CodeMirror Placeholder via JS


I'm using CodeMirror version 5.51 along with the placeholder addon. The placeholder itself is set like this.

<textarea id="code" class="hidden" placeholder="Paste your XML here..."></textarea>

When the user now changes the website's language, I would like to change the placeholder's text as well.

I've tried setting the placeholder directly

this.$editor.options.placeholder = "New value"

but this does not take effect immediately.

Is there a way to

  1. Specify a function that returns the string instead of a string directly?
  2. Re-initialize the placeholder through a function call?

The addon's code suggest that you can use something else than a string but I could not find more information on that subject.


Solution

  • You can use the cm.setOption() method to programmatically update the placeholder text, i.e.:

    this.$editor.setOption('placeholder', 'New value');
    

    Here is a proof-of-concept example:

    const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
      lineNumbers: true
    });
    
    document.getElementById('update-placeholder-text').addEventListener('click', () => {
      editor.setOption('placeholder', document.getElementById('placeholder-text').value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/display/placeholder.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.css" rel="stylesheet" />
    
    <input type="text" id="placeholder-text" value="Lorem ipsum" /><button id="update-placeholder-text">Update placeholder text</button>
    <hr />
    <textarea id="code" name="code" placeholder="Code goes here..."></textarea>