-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript.html
More file actions
546 lines (453 loc) · 14.8 KB
/
javascript.html
File metadata and controls
546 lines (453 loc) · 14.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Programming & Interactivity with JavaScript (for Researchers)</title>
<link rel="stylesheet" href="style/style.css" />
<script src="js/index.js"></script>
</head>
<body>
<div id="nav-placeholder"></div>
<div class="layout">
<aside class="sidebar">
<h2>Workshop</h2>
<nav>
<ul>
<li><a href="#overview">Overview</a></li>
<li><a href="#setup">Setup</a></li>
<li><a href="#js-role">What JavaScript Does</a></li>
<li><a href="#basics">JavaScript Basics</a></li>
<li><a href="#functions">Loops and Functions</a></li>
<li> <a href="#exercise_1">Mini Exercise</a>
</li>
<li><a href="#dom">DOM & Interactivity</a></li>
<li><a href="#exercise_2">Mini Exercise</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#element_loop">Element Loop</a></li>
<li><a href="#tabs">Tabs</a></li>
</ul>
</nav>
</aside>
<main class="content">
<header>
<h1>Web Programming & Interactivity with JavaScript</h1>
<p class="subtitle">A 2-hour introduction for researchers building interactive web content</p>
</header>
<section id="overview">
<h2>Overview</h2>
<p>This workshop introduces <strong>JavaScript</strong> as the programming layer of the web, starting from <a href="examples/lesson_1.zip">lesson_1.zip</a>
You should already have basic familiarity with HTML and CSS prior to proceeding.</p>
<ul>
<li><strong>Duration:</strong> 2 hours</li>
<li><strong>Prerequisites:</strong> Basic HTML & CSS</li>
<li><strong>Outcome:</strong> Added interactivity to webpage</li>
</ul>
</section>
<section id="setup">
<h2>Setup</h2>
<p>You may use the same environment as the <a href="index.html">HTML/CSS workshop</a>.
Please create a js>index.js file so you have all the files below in your website folder.
</p>
<li><code>index.html</code></li>
<li><code>style>style.css</code></li>
<li><code>js>index.js</code></li>
</ul>
</li>
</ul>
<p>
To load this index.js file within your webpage add the following line to the <i><head></i> element of your HTML file:
<pre><code id="code-container"><script src="js/index.js"></script></code></pre>
</p>
</section>
<section id="js-role">
<h2>The Role of JavaScript</h2>
<p>JavaScript enables <strong>behavior and interactivity</strong> on the web.</p>
<ul>
<li>Responding to user actions</li>
<li>Showing or hiding content</li>
<li>Updating pages without reloading</li>
<li>Supporting interactive figures, maps, and tools</li>
<li>Interactive data visualizations</li>
<li>Search and filtering interfaces</li>
<li>Demonstration tools and calculators</li>
</ul>
</section>
<section id="basics">
<h2>JavaScript Basics</h2>
<p>JavaScript is a programming language that runs in the browser.</p>
<h3>Variables</h3>
<p>Declare variables using <i>let</i>, <i>const</i> (for contants), or (older) <i>var</i>.</p>
<pre><code>// A simple variable
let projectTitle = "Weather Data Explorer";
// Logging output
console.log(projectTitle);</code></pre>
<p>To see console.log information:
In Chrome - click View>Developer>Developer Tools, then select <b>Console</b>.</p>
<p>Variable names must:</p>
<ul>
<li>Start with a letter, _, or $</li>
<li>Contain only letters, numbers, _, or $</li>
<li>Not start with a number</li>
<li>Not be a reserved keyword</li>
</ul>
<p>JavaScript is case-sensitive. So variables named 'age' and 'Age' are different. Best to keep variables in consistent case (e.g., camelCase).</p>
<h4>Variable Types</h4>
<h5>String</h5>
<pre><code>
let name = "Kevin";
let greeting = 'Hello';
let message = `Hi ${name}`; // template string
</code></pre>
<h5>Number</h5>
<pre><code>
let age = 42;
let price = 19.99;
let infinity = Infinity;
let notANumber = NaN;
</code></pre>
<h5>Boolean</h5>
<pre><code>
let isLoggedIn = true;
let isAdmin = false;
</code></pre>
<h5>Object</h5>
Key–value pairs.
<pre><code>
const user = {
name: "Kevin",
role: "Researcher"
};
//to get the 'name' key (two ways)
console.log(user.name, user['name'])
</code></pre>
<h5>Array</h5>
Ordered lists (arrays are objects).
<pre><code>
const numbers = [1, 2, 3, 4];
//to get the first value in the array
console.log(numbers[0])
</code></pre>
<h5>Date</h5>
For working with dates and times.
<pre><code>
const today = new Date();
</code></pre>
<h5>Undefined and Null</h5>
<pre><code>
let result;
console.log(result); // undefined
let selectedItem = null;
</code></pre>
</section>
<section id="functions">
<h2>Functions, Conditionals and Loops</h2>
<h3>Functions</h3>
<pre><code>// A basic function
function greetUser(name) {
return "Welcome, " + name;
}</code></pre>
<pre><code>// As an arrow function
// structure: const functionName = (parameters) => { function body };
const greetUser = (name) => {
return "Welcome, " + name;
};</code></pre>
<pre><code>// since it’s a one-liner, the extra braces and return are optional
const greetUser = name => "Welcome, " + name;</code></pre>
<h3>Conditionals</h3>
<h4>if</h4>
<pre><code>const temperature = 85;
if (temperature > 80) {
console.log("It's hot outside");
}
</code></pre>
<h4>if / else</h4>
<pre><code>const isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in");
}
</code></pre>
<h4>if / else if / else</h4>
<pre><code>const score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
</code></pre>
<h4>Comparison operators in conditionals</h4>
<pre><code>5 === 5 // true (strict equality)
5 == "5" // true (type coercion – usually avoid)
5 !== 3 // true
10 > 3 // true
5 <= 5 // true
</code></pre>
<h4>Logical operators (&&, ||, !)</h4>
<pre><code>const isAdmin = true;
const isLoggedIn = true;
if (isAdmin && isLoggedIn) {
console.log("Access granted");
}
///
const hasTicket = false;
const isVIP = true;
if (hasTicket || isVIP) {
console.log("You may enter");
}
</code></pre>
<h4>Switch Statement</h4>
Good when comparing one value against many options.
<pre><code>
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Almost weekend");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek day");
}
</code></pre>
<h3>Loops</h3>
<h4>for loop (classic)</h4>
<pre><code>for (let i = 0; i < 5; i++) {
console.log(i);
}
</code></pre>
<h4>Looping through an array with for</h4>
<pre><code>const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
</code></pre>
<h4>for...of (modern & clean)</h4>
Best for looping over values in arrays and strings.
<pre><code>const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
</code></pre>
<h4>for...in (objects)</h4>
<pre><code>const user = {
name: "Kevin",
role: "Researcher"
};
for (const key in user) {
console.log(key, user[key]);
}
</code></pre>
<h4>while loop</h4>
Runs while a condition is true.
<pre><code>let count = 0;
while (count < 3) {
console.log(count);
count++;
}
</code></pre>
<h4>do...while</h4>
Runs at least once, even if the condition is false.
<pre><code>let num = 5;
do {
console.log(num);
num++;
} while (num < 3);
</code></pre>
<h4>break and continue</h4>
<pre><code>for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skip 3
}
if (i === 5) {
break; // stop loop
}
console.log(i);
}
</code></pre>
<h4>Array methods (loops you’ll actually use a lot)</h4>
<h5>Array methods (loops you’ll actually use a lot)</h5>
<pre><code>const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2);
});
</code></pre>
<h5>map</h5>
Creates a new array.
<pre><code>
const tempsC = [0, 10, 20];
const tempsF = tempsC.map(c => (c * 9/5) + 32);
</code></pre>
<h5>filter</h5>
Keeps items that match a condition.
<pre><code>
const scores = [55, 78, 92, 60];
const passing = scores.filter(score => score >= 70);
</code></pre>
<h5>reduce</h5>
Accumulates values into one result.
<pre><code>
const data = [10, 20, 30];
const total = data.reduce((sum, value) => sum + value, 0);
</code></pre>
</section>
<section id="exercise_1">
<h2>Mini Exercise (5–7 min)</h2>
<p>From within your <i>index.js</i> file, write and test a function called 'fToC' that converts fahrenheit to celsius</p>
<pre><code>//Step 1: create fahrenheit to celsius function noting celsius = (fahrenheit - 32) * 5 / 9
// Step 2: test the function with different values to make sure it works as expected
</code></pre>
When you're done, save the file and test it in your web browser.
</section>
<section id="dom">
<h2>The DOM: Connecting JavaScript to HTML</h2>
<p>The <strong>Document Object Model (DOM)</strong> allows JavaScript to read and change HTML.</p>
<p>To make sure the HTML elements are present before the JavaScript runs,
be sure to wait for the 'DOMContentLoaded' event to fire, see below</p>
<pre><code>document.addEventListener('DOMContentLoaded', () => {
// Select an element
const heading = document.querySelector("h1");
console.log(heading)
// Change its text
heading.textContent = projectTitle;
});</code></pre>
<p>Think of the DOM as a bridge between your HTML structure and JavaScript logic.</p>
</section>
<section id="events">
<h2>Events & User Interaction</h2>
<p>Events allow your page to respond to user actions such as clicks or typing.>
The following example shows how to show/hide an element:
</p>
<h3>HTML</h3>
<pre><code>
<button class="tab-button active" data-tab="forcast_table">
Table
</button>
<div id="forcast_table" class="tab-panel active">
Forcast Table
<div>
</code></pre>
<h3>JavaScript</h3>
<pre><code>
const button = document.querySelector(".tab-button");
const forcast_table = document.querySelector("#forcast_table");
button.addEventListener("click", () => {
forcast_table.hidden = !forcast_table.hidden;
});</code></pre>
</section>
<section id="exercise_2">
<h2>Mini Exercise (5–7 min)</h2>
<p>Create a button to call your fahrenheit to celsius conversion function</p>
<ul>
<li>Create button in HTML</li>
<li>Wait for <i>DOMContentLoaded</i> event</li>
<li>Add interactivity to button click event</li>
</ul>
When you're done, save the file and test it in your web browser.
</section>
<section id="element_loop">
<h2>Looping through DOM elements</h2>
<p>It may be beneficial to loop through all the elements on your webpage.
This allows you to add intereactivity to multiple elements without having to write code for each one.
Here's how you can accomplish this:</p>
<pre><code>
const buttons = document.querySelectorAll('.tab-button');
buttons.forEach(button => {
button.addEventListener("click", () => {
console.log("Button clicked");
});
});
</code></pre>
More information on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll">querySelectorAll</a>
</section>
<section id="tabs">
<h2>Tabs</h2>
<p>Often times the web interface isn't large enough to show all the content at once. A common solution is to use tabs to show and hide different sections of content.
The following example shows how to show/hide different content sections using JavaScript and CSS.</p>
<h3>HTML</h3>
<pre><code>
<div class="tabs">
<button class="tab-button active" data-tab="forcast_table">
Table
</button>
<button class="tab-button" data-tab="forcast_chart">
Chart
</button>
</div>
<div class="tab-content">
<div id="forcast_table" class="tab-panel active">
Forcast Table
</div>
<div id="forcast_chart" class="tab-panel">
Forcast Chart
</div>
</div>
</code></pre>
<h3>CSS</h3>
<pre><code id="code-container0"></code></pre>
<script>
// The raw HTML code you want to display
var rawHTML = `
.tabs {
margin-bottom: 1rem;
}
.tab-button {
padding: 0.5rem 1rem;
border: none;
background: #e5e7eb;
cursor: pointer;
margin-right: 0.25rem;
}
.tab-button.active {
background: #2563eb;
color: white;
}
.tab-panel {
display: none;
}
.tab-panel.active {
display: block;
}
`;
// Set the textContent property to display the code as text
document.getElementById('code-container0').textContent = rawHTML;
</script>
<h3>JavaScript</h3>
<pre><code>
const buttons = document.querySelectorAll('.tab-button');
const panels = document.querySelectorAll('.tab-panel');
buttons.forEach(button => {
button.addEventListener('click', () => {
const target = button.dataset.tab;
// Update button states
buttons.forEach(b => b.classList.remove('active'));
button.classList.add('active');
// Update panel visibility
panels.forEach(panel => {
panel.classList.toggle(
'active',
panel.id === target
);
});
});
});</code></pre>
The complete code for this example can been seen at <a href="examples/lesson_2/">lesson 2</a>, and can be download from <a href="examples/lesson_2.zip">lesson_2.zip</a>.
</section>
<footer>Homework: From <a href="https://colostate-my.sharepoint.com/:w:/g/personal/kaworth_colostate_edu/IQD-Ek8LDhBqTZWcCkIuDPPCAaYqu3OVDHnDz9MgD64tVCk?e=0RdwIt">Getting Started With Web Design</a>
and complete part: 2) Organize Your Content.
<br><a href="apis_and_structured_data.html">Next Section</a>
</footer>
</main>
</div>
</body>
</html>