Search code examples
htmlcssbrowserpreview

Previewing a full HTML page inputted by a textarea


I am creating a templates application where users can write any HTML/CSS code inside a textarea (E.G. a full html page pasted on a textarea). These users are mostly familiar with html and css so we have not yet implemented markdown. One important feature that we would like to add is the ability to preview the html in the textarea before submition. I have thought of ways that these can be done, but I am not sure which would be correct and most maintainable.

  • Preview the html inside a div in the same page - the problem I can see here is the existing CSS style might interfere with the CSS styles the user typed in the textarea. Furthermore, if the user writes body tag in the textarea, there will be another body tag inside the existing body tag of the actual page, so the html might become malformed.
  • Preview the html on a separate window - the problem is I do not have much control on this (if the user uses a poppup blocker, for example)
  • Preview the html on a separate tab - the problem is the user might be confused (E.G. closes the whole browser, thinking that it opens in a new window)
  • Preview the html on an iframe - this is doable, but will require me to create an additional .html file just for previewing
  • Preview the html on a modal - this is doable, but I am not sure if modal bodies will accept toplevel tags like title or body

Can anyone help me? Which of these potential solutions are best? Or is there a better solution?


Solution

  • I would use an iframe. It can run a new body and html inside of it. So if someone for example styled the body in it, it wouldn't effect the page its on. Here I wrote the code for you. Give it a shot, do some html coding in the text area and click "run"

    <p>type some HTML/CSS code in here:</p>
    <textarea type="text" rows="15" cols="40"id="myText"></textarea>
    
    <p>Your HTML output</p>
    <iframe id="output" srcdoc="">
    </iframe>
    
    <p>Click the button to preview your code</p>
    
    <button onclick="myFunction()">run</button>
    
    <script>
    function myFunction() {
      var x = document.getElementById("myText").value;
      document.getElementById("output").srcdoc  = "<!doctype html> <html>" + x + "</html>";
    }
    </script>