Updating drawing with codemirror contents

Hi all,

Problem statement

I am struggling to understand how to pass the contents of a codemirror editor (when it’s updated manually on screen, by deleting or add new code) to a p5.js instance, on a button click.

In other words, how can I refresh and generate a new p5.js instance using only the current code from the codemirror instance on screen each time the button is pressed?

Issue detail

I’ve constructed the extremely basic code file below, it’s a simple HTML page, which has a loaded Codemirror File.

Every time ‘Update Code’ is pressed, it prints the current contents of the codemirror instance to the console. So for example, its possible to change the Ellipse size in the codemirror instance; pressing the button will then print this updated code to the console. I want that updated code to also be reflected in the p5js instance below.

Ultimate Aim

  • I would like to be able to refresh the p5.js output via the button click for any changes made to the codemirror instance


Please excuse any and all formatting / indenting (please open in codepen or the like):

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/mode/javascript/javascript.min.js"></script>

<link rel="stylesheet"

  <font size="4">
      <textarea id="jsCode">
  function setup() {
    createCanvas(400, 400);

  function draw() {

<script id="newx">
        editor = CodeMirror.fromTextArea(document.getElementById('jsCode'), {
            mode: 'javascript', 
            theme: 'dracula',
            electricChars: true,
            scrollbarStyle: "null",

          <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.js"></script>

          <p>Click the button to update the drawing</p>

          <button onclick="function3()">Run Code</button>


            function function3(){

Hi all - as an update what i’m effectively trying to do is literally exactly this (the run button):