-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlessons.html
More file actions
664 lines (576 loc) · 24.5 KB
/
lessons.html
File metadata and controls
664 lines (576 loc) · 24.5 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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Lessons - Interactive Learning Hub</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="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="css/educational-theme.css">
<style>
.lesson-modal {
display: none;
}
.lesson-modal.active {
display: flex;
}
.code-editor {
background: #1F2937;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
color: #F9FAFB;
resize: vertical;
min-height: 200px;
width: 100%;
}
.output-panel {
background: #111827;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
color: #10B981;
min-height: 100px;
overflow-y: auto;
}
</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-edu-blue font-semibold">Lessons</a>
<a href="playground.html" class="text-gray-700 hover:text-edu-blue transition-colors">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-12 bg-gradient-to-r from-edu-blue to-edu-purple">
<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 Learning Modules</h1>
<p class="text-xl opacity-90 max-w-3xl mx-auto">
Complete your JavaScript journey with our comprehensive, interactive lessons designed for all skill
levels.
</p>
</div>
</section>
<!-- Lessons Grid -->
<section class="py-16">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-8" id="lessons-grid">
<!-- Lessons will be populated by JavaScript -->
</div>
</div>
</section>
<!-- Lesson Modal -->
<div id="lesson-modal" class="lesson-modal fixed inset-0 bg-black bg-opacity-50 items-center justify-center z-50">
<div class="bg-white rounded-lg max-w-6xl w-full mx-4 max-h-screen overflow-y-auto">
<div class="p-6 border-b border-gray-200 flex justify-between items-center">
<h2 id="modal-title" class="text-2xl font-bold text-gray-900"></h2>
<button id="close-modal" class="text-gray-500 hover:text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12">
</path>
</svg>
</button>
</div>
<div class="p-6">
<div id="modal-content" class="space-y-6">
<!-- Content will be populated dynamically -->
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
<script>
// Lesson data
const lessons = [
{
id: 'variables',
title: '01. Variables & Data Types',
description: 'Learn about variable declarations, data types, and scope in JavaScript.',
difficulty: 'beginner',
color: 'from-edu-blue to-blue-600',
content: {
explanation: `Variables are containers for storing data values. In JavaScript, you can declare variables using let, const, or var keywords.`,
example: `// Variable declarations
let name = "John Doe";
let age = 25;
let isStudent = true;
let height = 5.8;
// Constants
const PI = 3.14159;
const COMPANY_NAME = "Tech Corp";
// Output variables
console.log("Name:", name);
console.log("Age:", age);
console.log("Is Student:", isStudent);
console.log("Height:", height);
console.log("PI:", PI);
// Check data types
console.log("Type of name:", typeof name);
console.log("Type of age:", typeof age);
console.log("Type of isStudent:", typeof isStudent);`,
exercise: `// Try this exercise:
// 1. Create a variable for your favorite movie
// 2. Create a variable for the year it was released
// 3. Create a boolean variable for whether you've watched it
// 4. Log all variables with descriptive messages
let favoriteMovie = ""; // Your code here
let releaseYear = 0; // Your code here
let hasWatched = false; // Your code here
console.log("My favorite movie is:", favoriteMovie);
console.log("It was released in:", releaseYear);
console.log("Have I watched it?", hasWatched);`
}
},
{
id: 'arithmetic',
title: '02. Arithmetic Expressions',
description: 'Master mathematical operations and calculations in JavaScript.',
difficulty: 'beginner',
color: 'from-edu-green to-green-600',
content: {
explanation: `Arithmetic operators allow you to perform mathematical calculations. JavaScript supports all basic mathematical operations.`,
example: `// Basic arithmetic operations
let a = 10;
let b = 5;
console.log("Addition:", a + b); // 15
console.log("Subtraction:", a - b); // 5
console.log("Multiplication:", a * b); // 50
console.log("Division:", a / b); // 2
console.log("Modulus:", a % b); // 0
console.log("Exponentiation:", a ** b); // 100000
// Order of operations (PEMDAS)
let result = 2 + 3 * 4;
console.log("2 + 3 * 4 =", result); // 14
let resultWithParens = (2 + 3) * 4;
console.log("(2 + 3) * 4 =", resultWithParens); // 20
// Increment and decrement
let counter = 0;
counter++; // Increment by 1
console.log("After increment:", counter); // 1
counter--; // Decrement by 1
console.log("After decrement:", counter); // 0`,
exercise: `// Calculate the area and circumference of a circle
const radius = 7;
const pi = 3.14159;
// Calculate area (π * r²)
let area = 0; // Your calculation here
// Calculate circumference (2 * π * r)
let circumference = 0; // Your calculation here
console.log("Radius:", radius);
console.log("Area:", area);
console.log("Circumference:", circumference);`
}
},
{
id: 'userinput',
title: '03. User Input',
description: 'Create interactive programs that respond to user input.',
difficulty: 'beginner',
color: 'from-edu-purple to-purple-600',
content: {
explanation: `User input allows your programs to be interactive. In browsers, we can use prompt() for simple input, or HTML forms for more complex interactions.`,
example: `// Simple user input with prompt (browser only)
// Note: prompt() works in browsers, not in this console
// Simulating user input for demonstration
let userName = "Alice"; // Normally: prompt("What's your name?");
let userAge = "25"; // Normally: prompt("What's your age?");
// Convert string input to number
let age = parseInt(userAge);
console.log("Hello, " + userName + "!");
console.log("You are " + age + " years old.");
// Template literals (modern approach)
console.log(\`Hello, \${userName}! You are \${age} years old.\`);
// Age category logic
if (age < 18) {
console.log("You are a minor.");
} else if (age < 65) {
console.log("You are an adult.");
} else {
console.log("You are a senior.");
}
// Working with HTML input (more common in web development)
// <input type="text" id="nameInput" placeholder="Enter your name">
// let inputValue = document.getElementById("nameInput").value;`,
exercise: `// Create a simple calculator
// Simulate getting two numbers from user
let num1 = "15"; // Normally from prompt() or input field
let num2 = "8"; // Normally from prompt() or input field
// Convert to numbers
let number1 = parseFloat(num1);
let number2 = parseFloat(num2);
// Perform calculations
let sum = 0; // Your code here
let difference = 0; // Your code here
let product = 0; // Your code here
let quotient = 0; // Your code here
console.log(\`\${number1} + \${number2} = \${sum}\`);
console.log(\`\${number1} - \${number2} = \${difference}\`);
console.log(\`\${number1} * \${number2} = \${product}\`);
console.log(\`\${number1} / \${number2} = \${quotient}\`);`
}
},
{
id: 'typeconversion',
title: '04. Type Conversion',
description: 'Learn to convert between different data types effectively.',
difficulty: 'beginner',
color: 'from-edu-yellow to-yellow-600',
content: {
explanation: `Type conversion (casting) is the process of converting one data type to another. JavaScript has both implicit (automatic) and explicit (manual) type conversion.`,
example: `// String to Number conversion
let strNumber = "123";
let num1 = Number(strNumber);
let num2 = parseInt(strNumber);
let num3 = parseFloat("123.45");
console.log("Original string:", strNumber, typeof strNumber);
console.log("Number():", num1, typeof num1);
console.log("parseInt():", num2, typeof num2);
console.log("parseFloat():", num3, typeof num3);
// Number to String conversion
let number = 456;
let str1 = String(number);
let str2 = number.toString();
let str3 = number + ""; // Implicit conversion
console.log("Original number:", number, typeof number);
console.log("String():", str1, typeof str1);
console.log("toString():", str2, typeof str2);
console.log("Implicit:", str3, typeof str3);
// Boolean conversion
let truthyValues = [1, "hello", [], {}];
let falsyValues = [0, "", null, undefined, false, NaN];
console.log("Truthy values:");
truthyValues.forEach(val => {
console.log(val, "=>", Boolean(val));
});
console.log("Falsy values:");
falsyValues.forEach(val => {
console.log(val, "=>", Boolean(val));
});`,
exercise: `// Type conversion practice
let userInput = "42.7";
let booleanString = "true";
let numberString = "100";
// Convert userInput to a number and round it
let roundedNumber = 0; // Your code here
// Convert booleanString to actual boolean
let actualBoolean = false; // Your code here (hint: compare with "true")
// Convert numberString to number and double it
let doubledNumber = 0; // Your code here
// Convert all results back to strings for display
let result1 = ""; // Your code here
let result2 = ""; // Your code here
let result3 = ""; // Your code here
console.log("Rounded number:", result1);
console.log("Boolean value:", result2);
console.log("Doubled number:", result3);`
}
},
{
id: 'constants',
title: '05. Constants',
description: 'Understand immutable variables and when to use const.',
difficulty: 'beginner',
color: 'from-red-500 to-red-600',
content: {
explanation: `Constants are variables that cannot be reassigned after declaration. Use const for values that shouldn't change and for better code clarity.`,
example: `// Basic constants
const PI = 3.14159;
const COMPANY_NAME = "TechCorp";
const MAX_USERS = 1000;
console.log("PI:", PI);
console.log("Company:", COMPANY_NAME);
console.log("Max users:", MAX_USERS);
// Constants with objects (content can change, reference cannot)
const person = {
name: "John",
age: 30
};
// This works (modifying content)
person.age = 31;
person.city = "New York";
console.log("Modified person:", person);
// This would cause an error (reassigning reference)
// person = {}; // TypeError!
// Constants with arrays
const colors = ["red", "green", "blue"];
console.log("Original colors:", colors);
// This works (modifying content)
colors.push("yellow");
colors[0] = "crimson";
console.log("Modified colors:", colors);
// This would cause an error (reassigning reference)
// colors = []; // TypeError!
// Best practices
const CONFIG = {
API_URL: "https://api.example.com",
TIMEOUT: 5000,
DEBUG_MODE: true
};
console.log("Configuration:", CONFIG);`,
exercise: `// Create a configuration object for a game
const GAME_CONFIG = {
// Add your properties here
PLAYER_LIVES: 0, // Set to 3
MAX_SCORE: 0, // Set to 999999
DIFFICULTY: "", // Set to "medium"
SOUND_ENABLED: false // Set to true
};
// Create an array of power-ups
const POWER_UPS = []; // Add: "speed", "shield", "double-score"
// Create constants for game boundaries
const MIN_X = 0; // Your value
const MAX_X = 0; // Set to 800
const MIN_Y = 0; // Your value
const MAX_Y = 0; // Set to 600
// Display all configuration
console.log("Game Config:", GAME_CONFIG);
console.log("Power-ups:", POWER_UPS);
console.log("Boundaries:", {MIN_X, MAX_X, MIN_Y, MAX_Y});
// Try modifying the arrays/objects (this should work)
POWER_UPS.push("extra-life");
GAME_CONFIG.PLAYER_LIVES = 5;
console.log("Modified config:", GAME_CONFIG);
console.log("Modified power-ups:", POWER_UPS);`
}
},
{
id: 'math',
title: '06. Math Object',
description: 'Explore the Math object for advanced mathematical operations.',
difficulty: 'beginner',
color: 'from-indigo-500 to-indigo-600',
content: {
explanation: `The Math object provides mathematical constants and functions. It's a built-in object that has properties and methods for mathematical constants and functions.`,
example: `// Math constants
console.log("Math.PI:", Math.PI);
console.log("Math.E:", Math.E);
// Rounding methods
let num = 4.7;
console.log("Original:", num);
console.log("Math.round():", Math.round(num)); // 5
console.log("Math.floor():", Math.floor(num)); // 4
console.log("Math.ceil():", Math.ceil(num)); // 5
// Min and Max
let numbers = [5, 2, 8, 1, 9];
console.log("Numbers:", numbers);
console.log("Math.min():", Math.min(...numbers)); // 1
console.log("Math.max():", Math.max(...numbers)); // 9
// Power and square root
let base = 3;
let exponent = 4;
console.log(\`\${base}^\${exponent} =\`, Math.pow(base, exponent)); // 81
console.log("Square root of 16:", Math.sqrt(16)); // 4
// Random numbers
console.log("Random 0-1:", Math.random());
console.log("Random 1-10:", Math.floor(Math.random() * 10) + 1);
console.log("Random 1-100:", Math.floor(Math.random() * 100) + 1);
// Trigonometry (radians)
let degrees = 90;
let radians = degrees * (Math.PI / 180);
console.log("sin(90°):", Math.sin(radians)); // 1
console.log("cos(90°):", Math.cos(radians)); // ~0
// Absolute value
console.log("Math.abs(-5):", Math.abs(-5)); // 5`,
exercise: `// Create a dice rolling simulation
function rollDice(sides) {
// Return random number between 1 and sides
return 0; // Your code here using Math.random() and Math.floor()
}
function rollMultipleDice(numberOfDice, sides) {
let results = [];
// Roll multiple dice and store results
// Your code here
return results;
}
// Test your functions
let singleRoll = rollDice(6);
let multipleRolls = rollMultipleDice(3, 6);
console.log("Single dice roll (6-sided):", singleRoll);
console.log("Three dice rolls:", multipleRolls);
console.log("Sum of three dice:", multipleRolls.reduce((a, b) => a + b, 0));
// Calculate circle properties
let radius = 5;
let area = 0; // π * r²
let circumference = 0; // 2 * π * r
let diameter = 0; // 2 * r
console.log(\`Circle with radius \${radius}:\`);
console.log("Area:", area.toFixed(2));
console.log("Circumference:", circumference.toFixed(2));
console.log("Diameter:", diameter);`
}
}
];
// Render lessons grid
function renderLessons() {
const grid = document.getElementById('lessons-grid');
grid.innerHTML = lessons.map(lesson => `
<div class="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow cursor-pointer lesson-card"
onclick="openLesson('${lesson.id}')">
<div class="bg-gradient-to-r ${lesson.color} p-4">
<h3 class="text-white font-bold text-lg">${lesson.title}</h3>
<span class="inline-block mt-2 px-2 py-1 bg-white bg-opacity-20 rounded-full text-xs text-white">
${lesson.difficulty}
</span>
</div>
<div class="p-6">
<p class="text-gray-600 mb-4">${lesson.description}</p>
<button class="text-edu-blue font-semibold hover:text-blue-600 transition-colors">
Start Lesson →
</button>
</div>
</div>
`).join('');
}
// Open lesson modal
function openLesson(lessonId) {
const lesson = lessons.find(l => l.id === lessonId);
if (!lesson) return;
document.getElementById('modal-title').textContent = lesson.title;
document.getElementById('modal-content').innerHTML = `
<div class="space-y-6">
<div>
<h3 class="text-lg font-semibold mb-3">📖 Explanation</h3>
<p class="text-gray-600 leading-relaxed">${lesson.content.explanation}</p>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">💡 Example</h3>
<div class="bg-gray-900 rounded-lg p-4">
<div class="flex items-center justify-between mb-3">
<span class="text-gray-400 text-sm">JavaScript</span>
<button onclick="copyCode(this)" class="text-gray-400 hover:text-white text-sm">
📋 Copy
</button>
</div>
<pre class="text-sm text-gray-100 overflow-x-auto"><code>${lesson.content.example}</code></pre>
</div>
<button onclick="runCode('${lessonId}', 'example')"
class="mt-3 bg-edu-green text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors">
▶ Run Example
</button>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">🎯 Practice Exercise</h3>
<textarea id="exercise-${lessonId}" class="code-editor w-full" placeholder="Write your code here...">${lesson.content.exercise}</textarea>
<div class="mt-3 flex gap-3">
<button onclick="runCode('${lessonId}', 'exercise')"
class="bg-edu-blue text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition-colors">
▶ Run Code
</button>
<button onclick="resetExercise('${lessonId}')"
class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-colors">
🔄 Reset
</button>
</div>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">📊 Output</h3>
<div id="output-${lessonId}" class="output-panel">
Click "Run Code" to see the output here...
</div>
</div>
</div>
`;
document.getElementById('lesson-modal').classList.add('active');
}
// Close lesson modal
function closeLesson() {
document.getElementById('lesson-modal').classList.remove('active');
}
// Run code function
function runCode(lessonId, type) {
const lesson = lessons.find(l => l.id === lessonId);
let code;
if (type === 'example') {
code = lesson.content.example;
} else {
code = document.getElementById(`exercise-${lessonId}`).value;
}
const outputDiv = document.getElementById(`output-${lessonId}`);
outputDiv.innerHTML = '';
// Capture console.log output
const originalLog = console.log;
const logs = [];
console.log = (...args) => {
logs.push(args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
).join(' '));
};
try {
// Execute the code
eval(code);
// Display output
if (logs.length > 0) {
outputDiv.innerHTML = logs.map(log => `<div class="mb-1">${log}</div>`).join('');
} else {
outputDiv.innerHTML = '<div class="text-gray-400">No output generated</div>';
}
} catch (error) {
outputDiv.innerHTML = `<div class="text-red-400">Error: ${error.message}</div>`;
} finally {
// Restore original console.log
console.log = originalLog;
}
}
// Reset exercise
function resetExercise(lessonId) {
const lesson = lessons.find(l => l.id === lessonId);
document.getElementById(`exercise-${lessonId}`).value = lesson.content.exercise;
document.getElementById(`output-${lessonId}`).innerHTML = 'Click "Run Code" to see the output here...';
}
// Copy code function
function copyCode(button) {
const codeBlock = button.parentElement.nextElementSibling.textContent;
navigator.clipboard.writeText(codeBlock).then(() => {
button.textContent = '✅ Copied!';
setTimeout(() => {
button.textContent = '📋 Copy';
}, 2000);
});
}
// Event listeners
document.getElementById('close-modal').addEventListener('click', closeLesson);
document.getElementById('lesson-modal').addEventListener('click', function (e) {
if (e.target === this) {
closeLesson();
}
});
// Initialize
renderLessons();
</script>
</body>
</html>