skip to Main Content

Here’s a basic HTML editor:

var textarea = document.querySelector('textarea'),
  iframe = document.querySelector('iframe');

function preview() {
  var iframeDoc = iframe.contentDocument;
  iframeDoc.open();
  iframeDoc.write(textarea.value);
  iframeDoc.close();
}

textarea.addEventListener('input', preview);
textarea,
iframe {
  width: 400px;
  height: 300px;
}
<textarea></textarea>
<iframe></iframe>

DEMO

It updates the HTML and CSS you put in the textarea, but you can’t use JavaScript const or let variables as it throws the following syntax error as soon as you edit the inserted code:

Identifier * has already been declared

To see what I mean, insert the following sample code in the textarea:

<!doctype html>
<html lang="en">
<head>
  <title>Sample Code</title>
</head>
<body>
  <p>Hello!</p>
  <script>
    const p = document.querySelector('p');
    p.style.color = 'blue';
  </script>
</body>
</html>

Now change Hello! to Hello, world!, or blue to red.

What’s the solution so the user can keep editing the code without getting that error?

2

Answers


  1. As far as I know, there is no way to un-declare variables in JS or remove them from a document’s scope. I’d suggest dynamically recreating an iframe element on each input event. Something like this:

    // index.js
    const textarea = document.querySelector("textarea");
    
    function preview() {
      const container = document.getElementById("iframe-container");
      const existing = document.querySelector("iframe");
    
      if (existing) existing.remove();
    
      const iframe = document.createElement("iframe");
      container?.appendChild(iframe);
      const iframeDoc = iframe?.contentDocument;
    
      iframeDoc?.open();
      iframeDoc?.write(textarea?.value ?? "");
      iframeDoc?.close();
    }
    
    textarea?.addEventListener("input", preview);
    
    <!-- index.html -->
    <textarea></textarea>
    <div id="iframe-container">
      <iframe></iframe>
    </div>
    
    Login or Signup to reply.
  2. Set your iframe’s srcdoc instead of reopening its Document:

    var textarea = document.querySelector('textarea'),
      iframe = document.querySelector('iframe');
    
    function preview() {
      iframe.srcdoc = textarea.value;
    }
    
    textarea.addEventListener('input', preview);
    textarea,
    iframe {
      width: 400px;
      height: 300px;
    }
    <textarea></textarea>
    <iframe></iframe>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search