Live Code Editor

Code

Live Preview

`; codeBlob = new Blob([htmlWrapper], { type: 'text/html' }); } else { // Otherwise, use the raw code codeBlob = new Blob([rawCode], { type: 'text/html' }); } // Create a URL for the Blob and set it as the iframe's source const blobUrl = URL.createObjectURL(codeBlob); livePreview.src = blobUrl; // Clean up the Blob URL when the iframe loads to prevent memory leaks livePreview.onload = () => { URL.revokeObjectURL(blobUrl); }; }; /** * Handles the file upload event, reading the file and * updating the editor's content. * @param {Event} event The file input change event. */ fileUpload.addEventListener('change', (event) => { const file = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = (e) => { const fileContent = e.target.result; // Update the textarea with the raw file content codeEditor.value = fileContent; // Store the file type on the editor element for later use const fileExtension = file.name.split('.').pop(); codeEditor.dataset.filetype = fileExtension; // Trigger an update to the live preview updatePreview(); }; reader.readAsText(file); } }); /** * Saves the content of the editor as a file to the user's device. */ saveButton.addEventListener('click', () => { const code = codeEditor.value; const blob = new Blob([code], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; // Set the filename based on the current file type const fileType = codeEditor.dataset.filetype; const filename = fileType === 'js' ? 'script.js' : 'index.html'; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }); // Update the preview whenever the user types or pastes content codeEditor.addEventListener('input', updatePreview); // Run the initial preview update when the page loads document.addEventListener('DOMContentLoaded', updatePreview);