Created
August 28, 2023 15:00
-
-
Save cferdinandi/dd9631993d33fd376a37136eb2fb6e4a to your computer and use it in GitHub Desktop.
Revisions
-
cferdinandi created this gist
Aug 28, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,102 @@ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Code Sandbox</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { margin: 1em auto; max-width: 40em; width: 88%; } label, textarea, iframe { display: block; width: 100%; } textarea { margin-bottom: 1.5em; min-height: 8em; } </style> </head> <body> <h1>Code Sandbox</h1> <label for="html">HTML</label> <textarea id="html" spellcheck="false" autocorrect="off" autocapitalize="off" translate="no"></textarea> <label for="css">CSS</label> <textarea id="css" spellcheck="false" autocorrect="off" autocapitalize="off" translate="no"></textarea> <label for="js">JavaScript</label> <textarea id="js" spellcheck="false" autocorrect="off" autocapitalize="off" translate="no"></textarea> <p><strong>Result</strong></p> <iframe id="result"></iframe> <script> // Get elements let html = document.querySelector('#html'); let css = document.querySelector('#css'); let js = document.querySelector('#js'); let result = document.querySelector('#result'); // Store debounce timer let debounce; /** * Update the iframe */ function updateIframe () { // Create new iframe let clone = result.cloneNode(); result.replaceWith(clone); result = clone; // Render result.contentWindow.document.open(); result.contentWindow.document.writeln( `${html.value} <style>${css.value}</style> <script type="module">${js.value}<\/script>` ); result.contentWindow.document.close(); } /** * Handle input events on our fields * @param {Event} event The event object */ function inputHandler (event) { // Only run on our three fields if ( event.target !== html && event.target !== css && event.target !== js ) return; // Debounce the rendering for performance reasons clearTimeout(debounce); // Set update to happen when typing stops debounce = setTimeout(updateIframe, 500); } // Listen for input events document.addEventListener('input', inputHandler); </script> </body> </html>