-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayground.html
More file actions
633 lines (560 loc) · 21 KB
/
playground.html
File metadata and controls
633 lines (560 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Playground - Interactive Code Editor</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'edu-blue': '#3B82F6',
'edu-green': '#10B981',
'edu-purple': '#8B5CF6',
'edu-yellow': '#F59E0B',
'edu-bg': '#F9FAFB',
'edu-text': '#374151'
}
}
}
}
</script>
<link rel="stylesheet" href="css/educational-theme.css">
<style>
.code-editor {
background: #1F2937;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', 'Monaco', 'Consolas', monospace;
color: #F9FAFB;
resize: none;
width: 100%;
min-height: 400px;
line-height: 1.5;
}
.output-panel {
background: #111827;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', 'Monaco', 'Consolas', monospace;
color: #10B981;
min-height: 200px;
overflow-y: auto;
white-space: pre-wrap;
}
.example-tab {
transition: all 0.3s ease;
}
.example-tab.active {
background: #3B82F6;
color: white;
}
</style>
</head>
<body class="bg-edu-bg text-edu-text">
<!-- Navigation -->
<nav class="bg-white shadow-lg fixed w-full z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<div class="flex-shrink-0 flex items-center">
<a href="index.html" class="flex items-center">
<span class="text-2xl font-bold text-edu-blue">JS</span>
<span class="text-2xl font-bold text-edu-purple ml-1">Learning Hub</span>
</a>
</div>
</div>
<div class="hidden md:flex items-center space-x-8">
<a href="index.html" class="text-gray-700 hover:text-edu-blue transition-colors">Home</a>
<a href="lessons.html" class="text-gray-700 hover:text-edu-blue transition-colors">Lessons</a>
<a href="playground.html" class="text-edu-blue font-semibold">Playground</a>
<a href="#exercises" class="text-gray-700 hover:text-edu-blue transition-colors">Exercises</a>
</div>
</div>
</div>
</nav>
<!-- Header -->
<section class="pt-20 pb-8 bg-gradient-to-r from-edu-green to-edu-blue">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-white">
<h1 class="text-4xl md:text-5xl font-bold mb-4">JavaScript Playground</h1>
<p class="text-xl opacity-90 max-w-3xl mx-auto">
Write, test, and experiment with JavaScript code in real-time. Perfect for learning and prototyping!
</p>
</div>
</section>
<!-- Main Playground -->
<section class="py-8">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- Toolbar -->
<div class="bg-white rounded-lg shadow-md p-4 mb-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex flex-wrap gap-2">
<button onclick="runCode()"
class="bg-edu-green text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors flex items-center gap-2">
▶ Run Code
</button>
<button onclick="clearCode()"
class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-colors">
🗑️ Clear
</button>
<button onclick="formatCode()"
class="bg-edu-blue text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition-colors">
✨ Format
</button>
<button onclick="shareCode()"
class="bg-edu-purple text-white px-4 py-2 rounded-lg hover:bg-purple-600 transition-colors">
📤 Share
</button>
</div>
<div class="flex items-center gap-4">
<select id="fontSize" onchange="changeFontSize()"
class="border border-gray-300 rounded px-3 py-1">
<option value="12">12px</option>
<option value="14" selected>14px</option>
<option value="16">16px</option>
<option value="18">18px</option>
</select>
<label class="flex items-center gap-2">
<input type="checkbox" id="autoRun" onchange="toggleAutoRun()">
<span class="text-sm">Auto Run</span>
</label>
</div>
</div>
</div>
<!-- Code Examples Tabs -->
<div class="bg-white rounded-lg shadow-md mb-6">
<div class="border-b border-gray-200 p-4">
<h3 class="text-lg font-semibold mb-3">📚 Quick Examples</h3>
<div class="flex flex-wrap gap-2" id="example-tabs">
<!-- Tabs will be populated by JavaScript -->
</div>
</div>
</div>
<!-- Editor and Output Grid -->
<div class="grid lg:grid-cols-2 gap-6">
<!-- Code Editor -->
<div class="bg-white rounded-lg shadow-md">
<div class="border-b border-gray-200 p-4">
<div class="flex items-center justify-between">
<h3 class="text-lg font-semibold flex items-center gap-2">
💻 JavaScript Editor
</h3>
<div class="flex items-center gap-2">
<span class="text-sm text-gray-500" id="line-count">Line 1</span>
<span class="text-sm text-gray-500" id="char-count">0 chars</span>
</div>
</div>
</div>
<div class="p-4">
<textarea id="code-editor" class="code-editor" placeholder="// Write your JavaScript code here...
console.log('Hello, World!');
// Try some examples:
// Variables
let name = 'JavaScript';
let version = 2024;
// Functions
function greet(name) {
return `Hello, ${name}!`;
}
// Call the function
let message = greet(name);
console.log(message);
// Arrays and loops
let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
console.log(`Number: ${num}`);
}"></textarea>
</div>
</div>
<!-- Output Panel -->
<div class="bg-white rounded-lg shadow-md">
<div class="border-b border-gray-200 p-4">
<div class="flex items-center justify-between">
<h3 class="text-lg font-semibold flex items-center gap-2">
📊 Output Console
</h3>
<button onclick="clearOutput()" class="text-gray-500 hover:text-gray-700">
🗑️ Clear
</button>
</div>
</div>
<div class="p-4">
<div id="output-panel" class="output-panel">
Welcome to the JavaScript Playground!
Click "Run Code" to execute your JavaScript code.
</div>
</div>
</div>
</div>
<!-- Tips Section -->
<div class="mt-8 bg-white rounded-lg shadow-md p-6">
<h3 class="text-lg font-semibold mb-4 flex items-center gap-2">
💡 Playground Tips
</h3>
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
<div class="p-4 bg-blue-50 rounded-lg">
<h4 class="font-semibold text-edu-blue mb-2">Console Output</h4>
<p class="text-sm text-gray-600">Use <code>console.log()</code> to display results in the output
panel.</p>
</div>
<div class="p-4 bg-green-50 rounded-lg">
<h4 class="font-semibold text-edu-green mb-2">Quick Examples</h4>
<p class="text-sm text-gray-600">Click on the example tabs above to load pre-written code
snippets.</p>
</div>
<div class="p-4 bg-purple-50 rounded-lg">
<h4 class="font-semibold text-edu-purple mb-2">Auto Run</h4>
<p class="text-sm text-gray-600">Enable auto-run to execute code automatically as you type (with
delay).</p>
</div>
</div>
</div>
</div>
</section>
<script>
// Code examples
const codeExamples = {
variables: {
title: "Variables",
code: `// Variable declarations
let name = "Alice";
let age = 25;
const PI = 3.14159;
// Output variables
console.log("Name:", name);
console.log("Age:", age);
console.log("PI:", PI);
// Variable operations
let x = 10;
let y = 5;
console.log("x + y =", x + y);
console.log("x * y =", x * y);`
},
functions: {
title: "Functions",
code: `// Function declaration
function greet(name) {
return \`Hello, \${name}!\`;
}
// Arrow function
const add = (a, b) => a + b;
// Function calls
console.log(greet("World"));
console.log("5 + 3 =", add(5, 3));
// Function with multiple parameters
function calculateArea(length, width) {
return length * width;
}
let area = calculateArea(10, 5);
console.log("Area:", area);`
},
arrays: {
title: "Arrays",
code: `// Array creation
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
console.log("Fruits:", fruits);
console.log("Numbers:", numbers);
// Array methods
fruits.push("grape");
console.log("After push:", fruits);
let doubled = numbers.map(n => n * 2);
console.log("Doubled:", doubled);
// Array iteration
console.log("\\nLoop through fruits:");
for (let fruit of fruits) {
console.log("-", fruit);
}`
},
objects: {
title: "Objects",
code: `// Object creation
let person = {
name: "John Doe",
age: 30,
city: "New York",
hobbies: ["reading", "coding", "gaming"]
};
console.log("Person:", person);
console.log("Name:", person.name);
console.log("Age:", person.age);
// Object methods
person.greet = function() {
return \`Hi, I'm \${this.name}!\`;
};
console.log(person.greet());
// Adding properties
person.email = "john@example.com";
console.log("Updated person:", person);`
},
loops: {
title: "Loops",
code: `// For loop
console.log("For loop (1 to 5):");
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// While loop
console.log("\\nWhile loop countdown:");
let countdown = 5;
while (countdown > 0) {
console.log("T-minus", countdown);
countdown--;
}
console.log("Blast off! 🚀");
// For...of loop
let colors = ["red", "green", "blue"];
console.log("\\nColors:");
for (let color of colors) {
console.log("-", color);
}`
},
conditionals: {
title: "Conditionals",
code: `// If statements
let age = 18;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive!");
} else if (age >= 18) {
console.log("You need a license to drive.");
} else {
console.log("You're too young to drive.");
}
// Switch statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week!");
break;
case "Friday":
console.log("TGIF!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Regular weekday");
}
// Ternary operator
let weather = "sunny";
let activity = weather === "sunny" ? "go to the beach" : "stay inside";
console.log("Today's plan:", activity);`
},
async: {
title: "Async/Await",
code: `// Simulating async operations
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchData() {
console.log("Fetching data...");
await delay(1000);
return { id: 1, name: "Sample Data" };
}
// Using async/await
async function main() {
try {
let data = await fetchData();
console.log("Data received:", data);
} catch (error) {
console.log("Error:", error);
}
}
main();
// Promise example
console.log("Starting promise...");
delay(500).then(() => {
console.log("Promise resolved after 500ms!");
});`
}
};
let autoRunEnabled = false;
let autoRunTimeout;
// Initialize the playground
function initPlayground() {
renderExampleTabs();
updateStats();
// Add event listeners
const editor = document.getElementById('code-editor');
editor.addEventListener('input', () => {
updateStats();
if (autoRunEnabled) {
clearTimeout(autoRunTimeout);
autoRunTimeout = setTimeout(runCode, 1000);
}
});
// Auto-run initial code
setTimeout(runCode, 500);
}
// Render example tabs
function renderExampleTabs() {
const tabsContainer = document.getElementById('example-tabs');
tabsContainer.innerHTML = Object.keys(codeExamples).map(key => `
<button onclick="loadExample('${key}')"
class="example-tab px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
${codeExamples[key].title}
</button>
`).join('');
}
// Load example code
function loadExample(exampleKey) {
const example = codeExamples[exampleKey];
if (example) {
document.getElementById('code-editor').value = example.code;
updateStats();
runCode();
// Update active tab
document.querySelectorAll('.example-tab').forEach(tab => {
tab.classList.remove('active');
});
event.target.classList.add('active');
}
}
// Run code function
function runCode() {
const code = document.getElementById('code-editor').value;
const outputPanel = document.getElementById('output-panel');
// Clear previous output
outputPanel.innerHTML = '';
// Capture console.log output
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
const logs = [];
console.log = (...args) => {
logs.push({
type: 'log',
content: args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
).join(' ')
});
};
console.error = (...args) => {
logs.push({
type: 'error',
content: args.map(arg => String(arg)).join(' ')
});
};
console.warn = (...args) => {
logs.push({
type: 'warn',
content: args.map(arg => String(arg)).join(' ')
});
};
try {
// Add timestamp
logs.push({
type: 'info',
content: `[${new Date().toLocaleTimeString()}] Code execution started...`
});
// Execute the code
eval(code);
logs.push({
type: 'info',
content: `[${new Date().toLocaleTimeString()}] Code execution completed.`
});
} catch (error) {
logs.push({
type: 'error',
content: `Error: ${error.message}`
});
} finally {
// Restore original console methods
console.log = originalLog;
console.error = originalError;
console.warn = originalWarn;
}
// Display output
if (logs.length > 0) {
outputPanel.innerHTML = logs.map(log => {
let className = 'text-green-400';
if (log.type === 'error') className = 'text-red-400';
if (log.type === 'warn') className = 'text-yellow-400';
if (log.type === 'info') className = 'text-blue-400';
return `<div class="${className} mb-1">${log.content}</div>`;
}).join('');
} else {
outputPanel.innerHTML = '<div class="text-gray-400">No output generated</div>';
}
// Scroll to bottom
outputPanel.scrollTop = outputPanel.scrollHeight;
}
// Clear code
function clearCode() {
document.getElementById('code-editor').value = '';
clearOutput();
updateStats();
}
// Clear output
function clearOutput() {
document.getElementById('output-panel').innerHTML = 'Output cleared. Run your code to see results here.';
}
// Format code (basic)
function formatCode() {
const editor = document.getElementById('code-editor');
let code = editor.value;
// Basic formatting (this is a simple version)
code = code.replace(/;/g, ';\n');
code = code.replace(/{/g, ' {\n ');
code = code.replace(/}/g, '\n}');
code = code.replace(/\n\s*\n/g, '\n');
editor.value = code;
updateStats();
}
// Share code
function shareCode() {
const code = document.getElementById('code-editor').value;
if (navigator.share) {
navigator.share({
title: 'JavaScript Code',
text: code
});
} else {
// Fallback: copy to clipboard
navigator.clipboard.writeText(code).then(() => {
alert('Code copied to clipboard!');
});
}
}
// Change font size
function changeFontSize() {
const fontSize = document.getElementById('fontSize').value;
document.getElementById('code-editor').style.fontSize = fontSize + 'px';
}
// Toggle auto run
function toggleAutoRun() {
autoRunEnabled = document.getElementById('autoRun').checked;
if (autoRunEnabled) {
runCode();
}
}
// Update stats
function updateStats() {
const code = document.getElementById('code-editor').value;
const lines = code.split('\n').length;
const chars = code.length;
document.getElementById('line-count').textContent = `Line ${lines}`;
document.getElementById('char-count').textContent = `${chars} chars`;
}
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
runCode();
}
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
clearOutput();
}
});
// Initialize when page loads
document.addEventListener('DOMContentLoaded', initPlayground);
</script>
</body>
</html>