Introduction
Create your own browser-based code editor with real-time preview functionality. This comprehensive guide will walk you through building a complete solution with error handling and security features.
HTML Structure
<div class="editor-container">
<div class="code-panel">
<h3>HTML</h3>
<textarea id="htmlCode"></textarea>
<h3>CSS</h3>
<textarea id="cssCode"></textarea>
<h3>JavaScript</h3>
<textarea id="jsCode"></textarea>
<button onclick="updatePreview()">Run Code</button>
<div id="error" class="error"></div>
</div>
<iframe id="preview" sandbox="allow-scripts allow-same-origin"></iframe>
</div>
CSS Implementation
.editor-container {
display: flex;
gap: 20px;
margin: 20px 0;
}
.code-panel {
flex: 1;
background: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
textarea {
width: 100%;
height: 150px;
padding: 15px;
margin: 15px 0;
font-family: monospace;
border: 1px solid #ddd;
border-radius: 6px;
resize: vertical;
}
#preview {
flex: 1;
height: 600px;
border: 1px solid #ddd;
border-radius: 8px;
background: white;
}
JavaScript Logic
function updatePreview() {
const errorDisplay = document.getElementById('error');
errorDisplay.textContent = '';
try {
const html = document.getElementById('htmlCode').value;
const css = document.getElementById('cssCode').value;
const js = document.getElementById('jsCode').value;
const iframe = document.getElementById('preview');
const doc = iframe.contentWindow.document;
doc.open();
doc.write(`
<!DOCTYPE html>
<html>
<head>
<style>${css}</style>
</head>
<body>
${html}
<script>
try {
${js}
} catch(e) {
parent.document.getElementById('error').textContent =
'JS Error: ' + e.message;
}
<\/script>
</body>
</html>
`);
doc.close();
} catch (e) {
errorDisplay.textContent = 'Editor Error: ' + e.message;
}
}
// Initialize and set up event listeners
updatePreview();
document.querySelectorAll('textarea').forEach(textarea => {
textarea.addEventListener('input', updatePreview);
});
Live Demo
HTML
CSS
JavaScript
Labels
Development