-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
895 lines (671 loc) · 46.6 KB
/
index.html
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>JS for Accessibility</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/source-code-pro/source-code-pro.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<!-- Jotted styles and scripts -->
<link rel="stylesheet" href="jotted/jotted.css">
<script src="jotted/jotted.js"></script>
</head>
<body>
<!--[if lte IE 9]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p>
<![endif]-->
<a href="#slide" class="skip sr-only focusable">Skip to slide</a>
<nav id="slide-control">
<button id="previous-slide" disabled aria-label="Previous slide">Previous slide</button>
<span aria-live="polite" aria-atomic="true">Slide <strong id="current-slide-counter">1</strong> of <strong id="total-slide-counter"></strong></span>
<button id="next-slide" aria-label="Next slide">Next slide</button>
</nav>
<main id="slide">
<!--
Insert slides here.
One per <article>, in the order you want.
They should all have an attribute of hidden except the first one. The script will do the rest!
-->
<article>
<h1>JavaScript for accessibility</h1>
<h2>Basics of JavaScript, what can go wrong and how to fix it</h2>
<p>Victor Loux</p>
<img src="images/abilitynet.jpg" alt="AbilityNet" style="width: 100%; max-width: 300px">
<label id="disable_code_mirror_label"><input type="checkbox" name="disable_code_mirror"> Disable the advanced code editor (check this if you are using a screen reader)</label>
</article>
<article hidden>
<img src="images/js.png" alt="" class="float-right">
<h2>What is JavaScript?</h2>
<ul>
<li>The programming language for the Web</li>
<li>A programming language is a way to <strong>give orders</strong> to a computer. It's a bit like a human language, but without ambiguity! Each programming language has vocabulary (keywords that each play a specific role) and grammar (rules defining how to write programs in that language).</li>
<!-- There's some nitpicking about whether HTML and CSS are 'programming language' since they're just a specification for publishing, they have no control flow -->
<li>Web pages use 3 main technologies: <strong title="HyperText Markup Language">HTML</strong> define the structure and the content, <strong title="Cascading Style Sheets">CSS</strong> define the styling, <strong title="JavaScript">JS</strong> allows us to add interactivity and dynamic content.</li>
<li>Despite the name: not related to Java!</li>
</ul>
</article>
<article hidden>
<img src="images/burrito.jpg" alt="" class="float-right">
<h2>What is a program?</h2>
<p>It's an ordered sequence of operations for solving a given problem. A program breaks down a complex problem into a series of simple operations. Here's a program that makes a burrito:</p>
<pre><code class="nohighlight">Begin
Get out the rice cooker
Fill it with rice
Fill it with water
Cook the rice
Chop the vegetables
Stir-fry the vegetables
Taste-test the vegetables
If the veggies are good
Remove them from the stove
If the veggies aren't good
Add more pepper and spices
If the veggies aren't cooked enough
Keep stir-frying the veggies
Heat the tortilla
Add rice to tortilla
Add vegetables to tortilla
Roll tortilla
End</code></pre>
<p>(This is not JavaScript!)</p>
<p>Notice the different types of actions here:</p>
<ul>
<li>simple actions ("get out the rice cooker")</li>
<li>conditional actions ("<em>if</em> the veggies are good")</li>
<li>actions that are repeated ("<em>keep</em> stir-frying the veggies")</li>
</ul>
</article>
<article hidden id="example-JS-event">
<h2>What can you do with JavaScript?</h2>
<p>The most interesting part of JavaScript is that it allows us to manipulate HTML and CSS in real time, and react to events in the browser. Check out the example below:</p>
<button>A magic button</button>
<div class="toggled-box red">This box is red</div>
<pre><code class="html"><div class="<mark>red</mark>">This box is <mark>red</mark></div></code></pre>
<h3>We are doing two things here:</h3>
<ul>
<li><strong>listen to the <code>click</code> event</strong> on the <code><button></code> element, and run some code when it is clicked</li>
<li>that code <strong>manipulates the HTML of our box</strong> to change the value of its <code>class</code> attribute, and the text it contains.</li>
</ul>
<p>Of course, <strong>this is a simplistic example</strong>, but you can do very complex things with JavaScript, such as loading content in real-time from a server without reloading the entire page, manipulating strings of text, hiding and showing elements on the page (e.g. menus, accordions), create custom interactive widgets, react to user input (keyboard, mouse and touch)…</p>
<p>When used correctly, JavaScript can greatly enhance the user experience. But if some users are not taken into consideration, <strong>it can make their experience worse</strong>. In the example above, we don't have live regions, so screen reader users are not aware that the text in the box has changed when they press the button. Another common occurence is working only with a mouse or touch, but not keyboard.</p>
</article>
<article hidden>
<h2>Instructions</h2>
<p>Below this paragraph is a console, which allows you to type some JavaScript code and immediately get the result. Try some simple instructions like <code>5 + 3</code>, or <code>40 * 28000</code>. To deal with text, you have to wrap it with quotations marks, <code>"like this"</code>. You can concatenate (add) two strings of text with the <code>+</code> operator: try it!</p>
<div class="console-container">
<div class="console"></div>
</div>
<p>We will talk more about this later, but you will need to remember that in JavaScript, you need to add a semicolon <code>;</code> after each instruction.</p>
</article>
<article hidden>
<h2>Variables</h2>
<p>In programming we use a lot of <strong>variables</strong>. These are “containers” that retain a certain value, and allows us to avoid repetition, or take data set by the user. Variables, as their name indicate, can change value over time.</p>
<p>Initialise a variable for the first time with the <code>var</code> keyword, followed by its name, then its value. For example <code>var age = 4</code>.</p>
<p>You can only <strong>initialise</strong> a variable once. To change its value after that, use an equal sign <code>=</code> operator, <strong>without</strong> the <code>var</code> keyword. Once you have variables you can then use them in place of a number, for example <code>age + 5</code>.</p>
<div class="console-container">
<div class="console"></div>
</div>
<h3>Types</h3>
<p>Variables can take many possible type of values, for instance:</p>
<ul>
<li>Numbers: for example <code>42</code> or <code>5.2</code></li>
<li>Strings: chains of characters surrounded by quotations marks, for example <code>"apples"</code></li>
<li>Boolean: this is either the values <code>true</code> or <code>false</code>. This is used very often for making logical statements and conditions; and remembering the <strong>state</strong> of something (for example "pressed or not").</li>
<li>Objects. We will talk about these later, but they are sort of “containers” that can contain variables and functions. You will see dots to access what's in an object, for example <code>person.name</code>.</li>
</ul>
<p>Try declaring multiple variable and adding them together. See what happens if you add a number to a string, or two strings together!</p>
<h3>Names</h3>
<p>You may notice there are some rules about how you can name a variable. Variable names may only contain letters, numbers (but not in the first position) and an underscore (_). See what happens if you try to declare variables called <code>my first name</code>, <code>name-of-the-user</code>, or <code>2nd_favourite_colour</code>.</p>
<p>It's good practice to give descriptive names, rather than single-letter variables like in maths (<code>x</code>, <code>y</code>, <code>a</code>…). A common thing to do is using a mix of uppercase and lowercase, for example <code>var myFavouriteFruit = "apple"</code>.</p>
</article>
<article hidden id="example-controlflow">
<h2>Conditions 1: introduction</h2>
<p>An important part of programming is having a <strong>control flow</strong>. This is where our program can make <strong>decisions</strong>. The most common way to do this is with an <strong>if-else</strong> statement.</p>
<pre><code class="nohighlight">If <mark>condition</mark> is true, <em>then</em>
do something
else
do something else</code></pre>
<p>The condition is always a <strong>boolean</strong> expression, i.e. it is either <code>true</code> or <code>false</code>. For example, <code>6 + 6 == 3</code> is false, but <code>6 + 6 == 12</code> is true. Of course there is little point in testing fixed values because they will always be true or false, but it becomes interesting with variables as we can change the behaviour dynamically.<p>
<p>Let's have an example. We will set a variable using the box below, to see if someone is over 18:</p>
<p><label><code>var age = </code><input type="number" name="value" length="3" value="15"><code>;</code></label></p>
<pre><code>if(age >= 18) {
<mark id="if-true">message = "You are an adult!";</mark>
} else {
<mark id="if-false">message = "Hang on there kiddo, you can't buy alcohol";</mark>
}</code></pre>
<p aria-live="polite"><code>message</code> is now "<span id="message-result"></span>".</p>
<h3>Let's break down the syntax</h3>
<ul>
<li><code>if (<em>condition</em>)</code> means "if the condition (what is between the parentheses) is true, then execute the following block".</li>
<li><code class="javascript">age >= 18</code> is the condition: it checks whether the variable <code>age</code> is greater than or equal to 18 (<code>>=</code> is like ≥ in maths).</li>
<li>The curly braces <code>{ ... }</code> define a <strong>block</strong>. They delimitate the start and end of what we want to run. They're used everywhere in JavaScript, not just for conditions. It's also important to know <strong>you can nest them</strong>!</li>
<li>The <strong>else</strong> statement say "if the condition above was false, then instead of running the block above, run this one instead." <strong>It is not mandatory</strong> to have an <code>else</code> statement; you can have a condition without it.</li>
</ul>
</article>
<article hidden id="example-controlflow2">
<h2>Conditions 2: operators, else if and nesting</h2>
<h3>Comparison operators</h3>
<p>In addition to the greater / lesser than operator (>, ≥, <, ≤) you will also encounter:</p>
<pre><code>if(age == 36) { … }</code></pre>
<p>This means "if the variable <code>age</code> is <strong>exactly equal to</strong>" 36. Note that to say "equal", we use <strong>two</strong> equal signs; this is because a single equal sign is used for assigning a value to a variable. If we wrote <code>age = 36</code> it would mean "set the variable <code>age</code> to be 36", instead of comparing two values.</p>
<pre><code>if(favouriteFruit != "banana") { … }</code></pre>
<p>This operator, <code>!=</code>, means <em>not equal to</em> (≠). You can use it to say what you <em>don't want</em>: it inverses the result.</p>
<h3>Nesting</h3>
<p>Here are are nesting several <code>if</code> statements. This allows us to have several conditions one after the other. If the user is under 18, then we check if they are 16 or over. If they are between 16 and 18, then we can check on another boolean variable (are they having a meal?): and if so we can give them a specific message. But this is a pretty long way to do it: we can also write it as...</p>
<pre><code>if(age < 18) {
if(age >= 16) {
if(isHavingAMeal == true) {
message = "OK, maybe you can if your parents are here...";
}
}
}</code></pre>
<h3>Else If</h3>
<p>You can test over more than one condition when using <code>else if(<em>condition</em>)</code>. Conditions are tested in order until one is true; if none of them is true, then it will fall back on the <code>else</code> block.</p>
<p><label><code>var weather = "<input type="text" name="weather" value="windy">";</code></label></p>
<pre><code>if (weather == "sunny") {
tip = "T-shirt time!";
} else if (weather == "windy") {
tip = "Windbreaker life.";
} else if (weather == "rainy") {
tip = "Bring that umbrella!";
} else if (weather == "snowy") {
tip = "Just stay inside!";
} else {
tip = "Not a valid weather type";
}</code></pre>
<p aria-live="polite"><code>tip</code> is now "<span id="message-result"></span>".</p>
</article>
<article hidden>
<h2>Conditions 3: logic operators</h2>
<pre><code>if(age < 18 <mark>&&</mark> age >= 16 <mark>&&</mark> isHavingAMeal == true) { … }</code></pre>
<p>The <code>&&</code> operator means <strong>AND</strong>. We can have expressions on both side of it, and the entire condition will only be true <string>if all</strong> the statements are true: is the user under 18, over 16, and is having a meal? If so, run the block.<br> There is also an operator for OR, which is two pipe signs (<code>||</code>):</p>
<pre><code>if(favouriteFruit == "orange" || favouriteFruit == "lemon") {
message = "Yum! Citrus!";
}</code></pre>
<p>The block above will run if <code>favouriteFruit</code> is <strong>either</strong> "orange" or "lemon", but not if it is anything else (like "apple" or "banana").</p>
<h3>Try it!</h3>
<p>Think you got it? Have a play below!</p>
<div class="bin bin-console">
<code class="code-js nohighlight"><!--// Type "message" in the console to see its value
var message;
var age = 23;
if(age >= 18) {
message = "Hello, fellow adult.";
} else {
message = "Hi kiddo!"
}
--></code>
</div>
<p>You can try to:</p>
<ul>
<li>Write an if block yourself</li>
<li>Declare some variables and use operators. You can type expressions directly in the console to see what happens: try <code>7 < 10</code>, <code>a < 16 && a > 18</code>…</li>
<li>Write an if-elseif-else statement which prints a different message if a variable is a negative number, zero, or positive.</li>
</ul>
</article>
<article hidden>
<h2>Functions</h2>
<p>Functions are another important aspect of code. They allow you to repeat the same block of code without having to copy and paste the same code over and over. Functions are first <strong>defined</strong> somewhere, this is when we define what they will do</p>
<pre><code>function sayHello() {
console.log("Hello, AbilityNet!")
}</code></pre>
<p>We have the keyword <strong>function</strong> to say what it is (a bit like <code>var</code>), and then the name of the function (<strong>sayHello</strong>), parentheses (we'll talk about these later) and braces to start a <strong>block</strong>, to define the start and end of the function code.<p>
<p>Once you've defined a function once, you can <strong>call</strong> it later in your program. This is done by using the name of the function with parentheses:</p>
<pre><code>sayHello();
sayHello();</code></pre>
<p>Our console will output:</p>
<pre><code>Hello, AbilityNet!
Hello, AbilityNet!</code></pre>
<p>Functions are interesting because they can also take <strong>arguments</strong>. This means what they do can depend on an input parameter. This is what the parentheses are for: they can contain a list of arguments. Our function <code>sayHello</code> did not have any argument, but we can define them in the definition and the call:</p>
<pre><code>function double(<mark>number</mark>) {
console.log(number * 2);
}
double(<mark>6</mark>); // 12
double(<mark>10</mark>); // 20
double(<mark>0.5</mark>); // 0.25</code></pre>
<p>(you may note that in the definition, we actually called a function called <code>console.log</code>, with a string as an argument. We'll talk about dots in function names later).</p>
<p>More arguments can be separated with a comma, like <code>add(number1, number2, number3)</code>. Try to define and call such function that adds 3 numbers below:</p>
<div class="bin bin-console">
<code class="code-js nohighlight"><!--function add(number1) {
console.log(number1);
}
// This should output 19
add(6, 10, 3);--></code>
</div>
</article>
<article hidden>
<h2>Selecting HTML elements from JavaScript</h2>
<p>We will now start to look at how JavaScript interacts with HTML and CSS. To modify elements on a page, we can first <strong>select</strong> an HTML element, in the same way that we do with CSS. We can then assign this HTML element to a variable, and then do things to that variable, like changing the text inside it, its attributes or CSS properties.</p>
<p>There are many ways to select HTML elements in JavaScript, but the easiest is <code>document.querySelector(<em>selector</em>)</code>, where <code>selector</code> is a string that contains a CSS selector. For example, <code>"#weekends"</code> for the element with an ID of "hidden", <code>".menuBar"</code> for elements with a class of "menuBar", or <code>"h2"</code> for all h2 elements.</p>
<p>The one downside of <code>document.querySelector</code> is that it will only select <strong>the first element</strong> that matches the given selector. If there are multiple elements on the page, we would need to use something <code>querySelectorAll</code>, but this requires using loops which we have not seen yet. Anyway, let's try it! Without touching the HTML pane, only the Javascipt code, try to get the second then the third box selected.</p>
<div class="bin">
<code class="code-html nohighlight"><!--<h1>My page heading</h1>
<div id="one">First box</div>
<div id="two">Second box</div>
<div id="three">Third box</div> --></code>
<code class="code-css nohighlight"><!--body {
background: ivory;
}
div {
border: 2px solid lightblue;
margin-bottom: 5px;
padding: 3px
} --></code>
<code class="code-js nohighlight"><!--// Select an element by ID
// and store it in a variable
var myElement = document.querySelector("#one");
// modify the style of that element
// we'll cover how this works later
myElement.style.color = "hotpink";
// and change its text
myElement.innerHTML = "Selected element!" --></code>
</div>
</article>
<article hidden>
<h2>Manipulating HTML from JavaScript: objects</h2>
<p>When we store an HTML element in a variable, its type is not a string or integer or boolean. It is instead what we call an <strong>object</strong>.</p>
<p>Objects are a relatively advanced programming concept, but to make it simple, variables that are objects can have their own “<strong>sub-variables</strong>”, which are actually called <em>properties</em>, and their own <strong>functions</strong>, which are called <em>methods</em>. If we had an object called <code>person</code>, we might have:</p>
<ul>
<li><code>person.name</code>, a property</li>
<li><code>person.age</code>, another property</li>
<li><code>person.sendMessage("Hey!")</code>, a method</li>
</ul>
<p>On the previous pages, we've seen an example of how properties and methods are used: with the <strong>dot notation</strong>. When we used <code>console.log()</code>, we actually used the <em>method</em> (function) called <code>log</code>, from the special object called <code>console</code>. The <code>console</code> object indeed has other methods we could use: <code>warn()</code>, <code>error()</code>…</p>
<p>Let's take the following HTML example:</p>
<pre><code class="nohighlight"><h2>Opening hours</h2>
<span class="highlight"><h3>Weekdays</h3></span>
…
<h3>Weekends</h3></code></pre>
<div class="example"><h2>Opening hours</h2>
<h3><span class="highlight">Weekdays</span></h3>
…
<h3>Weekends</h3></div>
<p>Now let's say we have selected the <strong>Weekdays</strong> heading element, and stored it into a variable called <span class="highlight"><code>weekdaysHeading</code></span>. This object has properties that will change <strong>only what is in this heading</strong>, and not others. For example, we can do:</p>
<pre><code>weekdaysHeading.style.color = "blue";</code></pre>
<p>And the result will be:</p>
<div class="example"><h2>Opening hours</h2>
<h3 style="color:blue"><span class="sr-only">Blue</span> Weekdays</h3>
…
<h3>Weekends</h3></div>
<p>Objects allow us to change things independently of other elements.</p>
<h3>Properties and methods for HTML objects</h3>
<p>There are a wide, but limited, amount of properties and methods you can use on objects that represent HTML elements. Most of the time, <strong>they map to the HTML attributes of the element</strong>. For example:</p>
<ul>
<li><code>element.style</code>, as we've seen above, is an object of its own — and each of its properties is the equivalent of a CSS property that can be set dynamically. For example <code>element.style.color</code> or <code>element.style.background</code>.</li>
<li>As we've said in the beginning, we cannot have hyphens in a variable or function name, so CSS properties like <code>font-size</code> and <code>margin-top</code> become <code>fontSize</code> and <code>marginTop</code>. The same is true for some attributes that we can set directly on the element: we can set <code>el.tabIndex</code> to modify the <code>tabindex</code> attribute.</li>
<li>To set attributes, the best option is to use the method <code>element.setAttribute(<em>attributeName</em>, <em>value</em>)</code>. For example, if we have a heading <code><h2>Contact</h2></code> and we call <code>myHeading.setAttribute("id", "call-us")</code>, then the HTML will become <code><h2 id="call-us">Contact</h2></code>.</li>
<li>You can also get the current value of an attribute, and store it into a variable. For this, use <code>element.getAttribute(<em>attributeName</em>)</code>.</li>
</ul>
<h3>Have a play!</h3>
<p>Try to select different elements and set attributes and styles dynamically. For reference, you may want to have a look at the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference" target="_blank">CSS properties reference<span class="sr-only"> (opens in new window)</span></a> for a list of things to test.</p>
<div class="bin">
<code class="code-html nohighlight"><!--<h1>My page heading</h1>
<div id="one">First box</div>
<div id="two">Second box</div>
<div id="three">Third box</div> --></code>
<code class="code-css nohighlight"><!--body {
background: ivory;
}
div {
border: 2px solid lightblue;
margin-bottom: 5px;
padding: 3px
} --></code>
<code class="code-js nohighlight"><!--// Select an element by ID
// and store it in a variable
var myElement = document.querySelector("#one");
// modify the style of that element
myElement.style.color = "hotpink";
// and its text
myElement.innerHTML = "Selected element!" --></code>
</div>
</article>
<article hidden>
<h2>Event handlers 1: event listeners</h2>
<p>Now that we've looked at functions and selecting HTML elements, we can start looking at <strong>event handlers.</strong> These are functions called when a specific <strong>event</strong> happens on an element that we've selected; an event can be a <strong>click</strong> (with a mouse, or touch on mobile), a key press, a value changing (e.g. a checkbox becoming unchecked), the mouse simply going over an element (without clicking), etc.</p>
<p>Consider the following HTML:</p>
<pre><code><button class="magic_button">Make box bigger</button>
<div class="box"></div></code></pre>
<button class="magic_button_off">Make box bigger</button>
<div class="box_off"></div>
<p>Of course, nothing happens yet when you press it. We cannot just set the size of the box in code anywhere, because it would expand immediately and not react to the button. We want to <strong>create a function</strong> that will make the box bigger, say <code>makeBoxBigger()</code>, and <strong>only call this function when the button is pressed</strong>.</p>
<p>This is done by using <code><em>element</em>.addEventListener(eventType, functionToCall)</code>. This is a method, applied to an element, as we've seen before. It says "keeps listening for <em>eventType</em> on this <em>element</em>. When this type of event happens, then call <em>functionToCall</em>".</p>
<p>So in our example, we'll have our element called <code>magicButton</code>, the <code>eventType</code> is going to be <code>click</code>, and the function is going to be <code>makeBoxBigger</code>. Let's try below:</p>
<div class="bin">
<code class="code-html nohighlight"><!--<button class="magic_button">Make box bigger</button>
<div class="box"></div>--></code>
<code class="code-css nohighlight"><!--.box {
height: 80px;
width: 80px;
background: lightsalmon;
border: 3px solid pink;
} --></code>
<code class="code-js nohighlight"><!--// Store elements in variables
var magicButton = document.querySelector('.magic_button');
var box = document.querySelector('.box');
// Keep track of the size of our box
var boxSize = 80;
// Create a function that will make our box bigger
// and store it in a variable!
var makeBoxBigger = function () {
boxSize += 20;
box.style.width = boxSize + 'px';
box.style.height = boxSize + 'px';
}
// Create an event handler
magicButton.addEventListener("click", makeBoxBigger);--></code>
</div>
</article>
<article hidden>
<h2>Event handlers 2: event types and keyboard accessibility</h2>
<p>In the example above, even though we used the <code>click</code> event, our button still worked when we pressed the Enter or Space key. This is thanks to a convenience of browsers which fire a click event on keyboard and touch input, <strong>but this only works on inputs and buttons</strong>. If we were to create a custom component, we will have to implement both events independently.</p>
<p>Other event types exist for keyboard and touch, and more specific events can be useful for special interaction. For example we can use <code>keyup</code> for when a key is released, <code>keydown</code> for when it is pressed, <code>touchstart</code> for when a finger starts pressing the screen… this allows us to create interactions like drag and drop, or games. For most keyboard-specific handlers, we are also able to get the specific key that was just pressed.</p>
<p><strong>Exercise time!</strong> Recreate the demo above, but this time we want different interactions on click and on keyboard. Create a function called <code>makeBoxSmaller()</code> by copying the function above and changing the + to a -, and copy the event listener to use a <code>keydown</code> event instead of <code>mousedown</code>.</p>
<div class="bin">
<code class="code-html nohighlight"><!--<div class="magic_button" tabindex="0" role="button">Click to make bigger, press key to make it smaller</div>
<div class="box">80</div>--></code>
<code class="code-css nohighlight"><!--.magic_button{
padding: 3px;
display: inline-block;
background: #eee;
border: 1px solid grey;
} .box {
height: 80px;
width: 80px;
background: lightsalmon;
border: 3px solid pink;
} --></code>
<code class="code-js nohighlight"><!--// Store elements in variables
var magicButton = document.querySelector('.magic_button');
var box = document.querySelector('.box');
// Keep track of the size of our box
var boxSize = 80;
// Create a function that will make our box bigger
// and store it in a variable!
var makeBoxBigger = function () {
boxSize += 20;
box.style.width = boxSize + 'px';
box.style.height = boxSize + 'px';
// Change text inside for screen reader users
box.innerHTML = boxSize;
}
// HERE: copy the function above and make the box smaller
// Create event handlers
magicButton.addEventListener("mouseup", makeBoxBigger); --></code>
</article>
<article hidden>
<h2>Moving focus programmatically</h2>
<p>One important method that we did not talk about yet is the <code>element.focus()</code> method. Calling <code>.focus()</code>, with no arguments, moves the focus to a specific element, just as if the user tabbed onto it.</p>
<div class="bin">
<code class="code-html nohighlight"><!--<h3>Try tabbing on the links below...</h3>
<a href="">My first link</a>,
<a href="" id="receiveFocus">my second link</a> and
<a href="">a third link</a>
<p>
<button id="giveFocus">
Click to give focus to the
second element
</button>
</p>--></code>
<code class="code-css nohighlight"><!--a:focus, button:focus {
outline: 2px solid orange;
} --></code>
<code class="code-js nohighlight"><!--// Store elements in variables
var giveFocusButton = document.querySelector('#giveFocus');
var receiveFocusLink = document.querySelector('#receiveFocus');
// Create an event handler
giveFocusButton.addEventListener("click", function() {
// call the .focus() method of our element
receiveFocusLink.focus();
});--></code>
</div>
<p>Being able to set focus programmatically can have bad consequences for accessibility: it <strong>breaks predictability</strong> for keyboard and screen reader users, particularly when it is not expected. It can be a breach of SC <a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/consistent-behavior-receive-focus.html" target="_blank">3.2.1 On Focus<span class="sr-only"> (opens in new window)</span></a> or <a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/consistent-behavior-unpredictable-change.html" target="_blank">3.2.2 On Input<span class="sr-only"> (opens in new window)</span></a> because it changes context when the user does not expected.</p>
<p>However, when used wisely it can be useful! A common example is a modal dialog. Let's see that on the next page…</p>
</article>
<article hidden>
<h2>Basics of ARIA</h2>
<p>Let's talk a bit about ARIA. ARIA stands for <strong>Accessible Rich Internet Applications</strong> and is an <strong>extension</strong> of HTML that allows us to make complex web applications and widgets more accessible to people who use Assistive Technology. With ARIA, we can define custom <strong>roles</strong>, <strong>states</strong>, <strong>names</strong> with the value of an element, which allows us to fulfill the success criteria <a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/ensure-compat-rsv.html" target="_blank">4.1.2 Name, Role, Value<span class="sr-only"> (opens in new window)</span></a> of the WCAG.</p>
<p>ARIA mostly adds new HTML attributes that start with <code>aria-</code>, as well as the special <code>role</code> attribute. A lot of the possible attributes are in fact already implicit in a lot of existing HTML elements. For example, <code><h3></code> is equivalent to writing <code><div role="heading" aria-level="3"></code>, and the <code><nav></code> element will be treated the same as <code><div role="navigation"></code>.</p>
<p>It would be redundant to write ARIA attributes on elements that already have semantics: and as Heydon Pickering says, <q>ARIA isn't for making HTML accessible, it's for making <em>inaccessible</em> HTML accessible</q>.</p>
<p>Sometimes, native HTML elements won't cut it, because of complex interactions or implementations. Examples that you will have encountered include <strong>accordions</strong>: the expanded or collapsed state needs to be communicated non-visually, and this can be achieved using <code>aria-expanded</code>. Text that changes elsewhere on the page needs to be announced, with <code>aria-live</code>. Tabs can be made accessible as such by using <code>role="tab"</code> and <code>aria-selected</code>, despite not having any native element for them in HTML.</p>
<p>Here's an example of an accordion button. Sometime ARIA elements need to remain the same and are set in HTML only, but sometimes they need to be changed in JS for it to make sense:</p>
<div class="bin">
<code class="code-html nohighlight"><!--<button id="expand_data" aria-expanded="false">View more data ▼</button>
<div id="my_data" hidden>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut accusantium esse praesentium ducimus minus, maxime cum sit voluptatum assumenda a amet at perferendis officiis optio quisquam quos officia eligendi asperiores!
</div> --></code>
<code class="code-css nohighlight"><!-- #my_data {
border: 1px solid blue;
padding: .4em;
margin-top: 1em
}
--></code>
<code class="code-js nohighlight"><!--var expandButton = document.querySelector('#expand_data');
var myData = document.querySelector('#my_data');
expandButton.addEventListener('click', function() {
// This will invert the value of the hidden attribute
myData.hidden = !myData.hidden;
// we update the value of aria-expanded
if(myData.hidden) {
expandButton.setAttribute('aria-expanded', "false");
expandButton.innerHTML = "View more data ▼";
} else {
expandButton.setAttribute('aria-expanded', "true");
expandButton.innerHTML = "View more data ▲";
}
}); --></code>
</div>
<p>Have a look at the code and now try to make the toggle button below accessible. At the moment, screen reader users do not know whether it is pressed or not; there is only a visual cue. Hint: use <code>aria-pressed</code>.</p>
<div class="bin">
<code class="code-html nohighlight"><!--<button id="pressable">I can be pushed!</button>--></code>
<code class="code-css nohighlight"><!-- #pressable {
border: 4px outset salmon;
font-size: 2em;
background-color: lightsalmon;
}
#pressable.pressed {
border: 4px inset salmon;
font-size: 2em;
background-color: darksalmon;
}
--></code>
<code class="code-js nohighlight"><!--var pressableButton = document.querySelector('#pressable');
// Here we edit an attribute directly:
// element.className edits the "class" attribute in CSS
pressableButton.addEventListener('click', function() {
if(pressableButton.className == "") {
pressableButton.className = "pressed";
} else {
pressableButton.className = "";
}
}); --></code>
</div>
</article>
<article hidden>
<h2>Example: modal dialogs</h2>
<p>Let's try to put it all together!</p>
<p>The following is an inaccessible modal dialog: the focus is not moved, the background receives focus with a screen reader and a keyboard. There is also no label on the close button.</p>
<div class="bin">
<code class="code-html nohighlight"><!-- <main id="backgroundContent">
<h1>Inaccessible modal dialogs</h1>
This is the background content. Pressing <button id="openModalButton">this button</button> will open a new modal dialog. While it's open, you should not be able to read this text with a screen reader, or tab on <a href="#">this link</a> or <input type="text" value="this input field">. But in this example, no effort was made to prevent this however, so screen reader users are able to navigate through the background, and they are not moved directly to the dialog when it opens.
</main>
<div id="modal" hidden>
<h2>This is a modal dialog</h2>
{-- the close button has no aria-label here: this is bad practice for screen readers users who will just hear "X, button" --}
<button id="closeModalButton">x</button>
You're in it. <a href="#">Here's a link</a>, which is harder to tab to for keyboard users -- as the focus remained in the back. Tabbing and SR cursor should be restrained to the contents of this modal dialog for as long as it is open. But they're not because this is not an accessible dialog.
</div>-->
</code>
<code class="code-css nohighlight"><!--body {
font-family: sans-serif;
}
#modal {
position: absolute;
width: 50%;
top: 8em;
left: 25%;
padding: 1em;
background: white;
border: 1px solid grey;
}
#closeModalButton {
position: absolute;
top: 1em;
right: 1em;
font-size: 1.6em;
}
/*
Make the background visually faint
In most real-life cases you'd have another overlay div in between
*/
.greyed-out {
opacity: 0.4;
}
#modal h2:focus {
outline: 0;
/* exceptionally this is acceptable here, because it is
not an interactive element; we only focus on it programmatically
to move the screen reader focus inside the dialog,
and announce the first element in it (this heading).
Having an outline could be confusing for sighted kbd users. */
}--></code>
<code class="code-js nohighlight"><!--var modalDialogContainer = document.querySelectorAll('div#modal')[0];
var backgroundContainer = document.querySelectorAll('main')[0];
var openModalButton = document.querySelectorAll('#openModalButton')[0];
var closeModalButton = document.querySelectorAll('#closeModalButton')[0];
var openDialog = function() {
// Make the dialog visible
modalDialogContainer.removeAttribute('hidden');
backgroundContainer.setAttribute("class", "greyed-out");
};
var closeDialog = function() {
// Hide the dialog
modalDialogContainer.setAttribute('hidden', 'hidden');
backgroundContainer.removeAttribute("class");
};
// Event handlers for buttons
openModalButton.addEventListener("click", openDialog);
closeModalButton.addEventListener("click", closeDialog); --></code>
</div>
<p>The following is a <strong>correctly implemented</strong>, accessible dialog:</p>
<div class="bin">
<code class="code-html nohighlight"><!-- <main id="backgroundContent">
<h1>Accessible modal dialogs</h1>
This is the background content. Pressing <button id="openModalButton">this button</button> will open a new modal dialog. While it's open, you should not be able to read this text with a screen reader, or tab on <a href="#">this link</a> or <input type="text" value="this input field">. This is because the background div will have an <code>aria-hidden</code> attribute, and all its interactive elements will get a <code>tabindex</code> of -1 to remove them from the focus order.
</main>
<div id="modal" hidden>
{-- here there is a tabindex of -1 to make this h2 focusable programatically, but not with the keyboard --}
<h2 tabindex="-1">This is a modal dialog</h2>
<button aria-label="Close dialog" id="closeModalButton">x</button>
You're in it. <a href="#">Here's a link</a>. Tabbing and SR cursor should be restrained to the contents of this modal dialog for as long as it is open.
</div> --></code>
<code class="code-css nohighlight"><!--body {
font-family: sans-serif;
}
#modal {
position: absolute;
width: 50%;
top: 8em;
left: 25%;
padding: 1em;
background: white;
border: 1px solid grey;
}
#closeModalButton {
position: absolute;
top: 1em;
right: 1em;
font-size: 1.6em;
}
/*
Make the background visually faint
In most real-life cases you'd have another overlay div in between
*/
#backgroundContent[aria-hidden="true"] {
opacity: 0.4;
}
#backgroundContent[aria-hidden="true"] a,
#backgroundContent[aria-hidden="true"] button,
#backgroundContent[aria-hidden="true"] input {
pointer-events: none;
}
#modal h2:focus {
outline: 0;
/* exceptionally this is acceptable here, because it is
not an interactive element; we only focus on it programmatically
to move the screen reader focus inside the dialog,
and announce the first element in it (this heading).
Having an outline could be confusing for sighted kbd users. */
}--></code>
<code class="code-js nohighlight"><!--var modalDialogContainer = document.querySelectorAll('div#modal')[0];
var backgroundContainer = document.querySelectorAll('main')[0];
var openModalButton = document.querySelectorAll('#openModalButton')[0];
var closeModalButton = document.querySelectorAll('#closeModalButton')[0];
var openDialog = function() {
// Make the dialog visible
modalDialogContainer.removeAttribute('hidden');
// Make the background element aria-hidden to prevent SR access
backgroundContainer.setAttribute('aria-hidden', 'true');
// Make the interactive elements in the background div have a tabindex of -1
backgroundContainer.querySelectorAll('a, button, input').forEach((el) => {
el.setAttribute('tabindex', '-1')
});
// Give focus to the heading in the newly opened dialog
document.querySelectorAll('#modal h2')[0].focus();
};
var closeDialog = function() {
// Hide the dialog
modalDialogContainer.setAttribute('hidden', 'hidden');
// Make background text visible to SR again
backgroundContainer.setAttribute('aria-hidden', 'false');
// Return default tabindex values to interactive elements
backgroundContainer.querySelectorAll('a, button, input').forEach((el) => {
el.removeAttribute('tabindex')
});
// Give focus back to the element we clicked before the modal opened
// This is important for SR users to avoid disorientation,
// and for kbd users to avoid having to tab through the whole page again:
// our focus is now in a hidden div, so it'll go back to the top of the page otherwise
openModalButton.focus();
};
// Event handlers for buttons
openModalButton.addEventListener("click", openDialog);
closeModalButton.addEventListener("click", closeDialog);
// close the dialog when the Esc key is pressed
document.addEventListener("keyup", function(e) {
e = e || window.event;
if(e.keyCode === 27) { // ESC
closeDialog();
}
});
--></code>
</div>
</article>
<article hidden>
<h2>Questions?</h2>
<h3>Doing more testing!</h3>
<a href="https://codepen.io">CodePen</a> is a tool similar to the code used in here, that allow you to quickly test HTML, CSS and JS in a single screen.
<p>The developer tools / web inspector (F12) have a console that will run in the <strong>context</strong> of the page.</p>
<h3>Sources and references</h3>
<ul>
<li><a href="https://openclassrooms.com/courses/learn-the-basics-of-javascript/introduction-to-programming">OpenClassrooms</a></li>
<li><a href="http://developer.mozilla.org">Mozilla Developer Network</a></li>
</ul>
</article>
</main>
<!-- Scripts -->
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/atom-one-light.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js" charset="utf-8"></script>
<script src="js/slides.js"></script>
<script src="https://static.jsbin.com/js/embed.min.js?4.0.4"></script>
<!-- <style media="screen" id="iframeheight">
iframe { height: auto; }
</style> -->
</body>
</html>