-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathj01_Javascript.txt
More file actions
978 lines (727 loc) · 29.3 KB
/
j01_Javascript.txt
File metadata and controls
978 lines (727 loc) · 29.3 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
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
Derek Banas 2015 - JavaScript Video Tutorial 1h37m
https://www.youtube.com/watch?v=fju9ii8YsGs
Note that Derek has also a more recent (2019)
set of 13 tutorials as a Playlist:
JavaScript Tutorial Real Projects
- https://www.youtube.com/watch?v=IyDVvGmzTlo&list=PLGLfVvz_LVvTP2Op3wZlaGTUcgCfDuwn8
// ----------------------------------------------------
1995 - Javascript was added to Netscape
1996 - Microsoft released JScript
2009 - ECMAScript ES5 standard
2015 - ECMAScript ES6 standard
The tutorial below is based on ES5 (2009)
Since then syntax has changed (with ES6 standard).
For example, let, const, arrow function, for ... in loop.
x = 3; // bad practice
var x; // bad practice
let x = 2; // good
let x; // good
const x = 2; // good
console.log("something")
var add1 = (x, y) => {return x + y;};
var add2 = (x, y) => x + y;
add1(1, 2); // 3
add2(1, 2); // 3
See more here:
.. https://www.javatpoint.com/es5-vs-es6#
.. https://en.wikipedia.org/wiki/JavaScript
.. https://en.wikipedia.org/wiki/JavaScript_syntax
// ----------------------------------------------------
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jstut.js"></script>
<style type="text/css">
body {font-size: 1.6em;}
.hidden {display:none;}
.show {display:inline !important;}
button {
border: 2px solid black; background: #E5E4E2;
font-size: .5em; font-weight: bold; color: black;
padding: .8em 2em;
margin-top: .4em;
}
</style>
</head>
<body>
<p id="sayHello"></p>
<script>
// You create variables that store values with var
// Prompt opens a popup that requests info
var yourName = prompt("What is your name?");
// If performs different actions depending on conditions
if(yourName != null){
// Set text in an HTML element with the id sayHello
// You concatenate (combine) strings with +
document.getElementById("sayHello").innerHTML = "Hello " + yourName;
} else {
// Alert opens a popup that contains a message
alert("Please Enter Your Name Next Time");
}
// ---------- VARIABLES ----------
// variable names can't start with a number, contain spaces, but can
// contain letters, numbers, underscores or $ (Are case sensitive)
var myName = "Derek";
var myAge = 40;
// Variables don't have a defined type, which can cause problems
myName = 100;
// ---------- MATH ----------
// document.write outputs data to the browser
document.write("5 + 4 = ", 5 + 4, "<br/>");
// Using + instead of , will treat everything as a string unless you use ()
document.write("5 + 4 = " + (5 + 4) + "<br/>");
document.write("5 - 4 = ", 5 - 4, "<br/>");
document.write("5 * 4 = ", 5 * 4, "<br/>");
document.write("5 / 4 = ", 5 / 4, "<br/>");
// Modulus remainder of a division
document.write("5 % 4 = ", 5 % 4, "<br/>");
var maxNum = Number.MAX_VALUE;
document.write("Max Num = ", maxNum, "<br/>");
document.write("Min Num = ", Number.MIN_VALUE, "<br/>");
// Numbers have 16 digits of precision
precisionTest = 0.1000000000000001;
document.write(precisionTest + 0.1000000000000001, "<br/>");
// Round number to 2 decimal places
var balance = 1563.87;
document.write("Monthly payment : ", (balance / 12).toFixed(2), "<br />");
var randNum = 5;
// Shortcut for adding 1
document.write("randNum++ = ", randNum++, "<br/>");
document.write("++randNum = ", ++randNum, "<br/>");
// The same exists for -
document.write("randNum-- = ", randNum--, "<br/>");
document.write("--randNum = ", --randNum, "<br/>");
// Perform a calculation on a value and assign the result
document.write("randNum += 5 = ", randNum += 5, "<br/>");
document.write("randNum -= 5 = ", randNum -= 5, "<br/>");
document.write("randNum *= 5 = ", randNum *= 5, "<br/>");
document.write("randNum /= 5 = ", randNum /= 5, "<br/>");
// Order of operations
document.write("3 + 2 * 5 = ", 3 + 2 * 5, "<br/>");
document.write("(3 + 2) * 5 = ", (3 + 2) * 5, "<br/>");
// Math properties and methods
document.write("Math.E = ", Math.E, "<br/>");
document.write("Math.PI = ", Math.PI, "<br/>");
document.write("Math.abs(-8) = ", Math.abs(-8), "<br/>");
document.write("Math.cbrt(1000) = ", Math.cbrt(1000), "<br/>");
document.write("Math.ceil(6.45) = ", Math.ceil(6.45), "<br/>");
document.write("Math.floor(6.45) = ", Math.floor(6.45), "<br/>");
document.write("Math.round(6.45) = ", Math.round(6.45), "<br/>");
document.write("Math.log(10) = ", Math.log(10), "<br/>"); // Natural log
document.write("Math.log10(10) = ", Math.log10(10), "<br/>"); // Base 10 log
document.write("Math.max(10,5) = ", Math.max(10,5), "<br/>");
document.write("Math.min(10,5) = ", Math.min(10,5), "<br/>");
document.write("Math.pow(4,2) = ", Math.pow(4,2), "<br/>");
document.write("Math.sqrt(1000) = ", Math.sqrt(1000), "<br/>");
document.write("Random # (1-10) = ", Math.floor((Math.random() * 10) + 1), "<br/>");
// Convert strings to numbers
document.write("Converted String : ", Number("3.14"), "<br />");
document.write("Converted Int : ", parseInt("5"), "<br />");
document.write("Converted Float : ", parseFloat("5.555"), "<br />");
// ---------- STRINGS ----------
var randStr = "A long " + "string that " + "goes on and on";
// String length
document.write("String Length : ", randStr.length + "<br/>");
document.write("Index for \"goes\" : ", randStr.indexOf("goes"), "<br/>");
// Return the value using a start and end index
document.write(randStr.slice(19, 23) + "<br/>");
// Return everything after the start index
document.write(randStr.slice(19) + "<br/>");
// Return the value using the start index and length
document.write(randStr.substr(19, 4) + "<br/>");
// Replace a string
document.write(randStr.replace("and on", "forever") + "<br/>");
// Get character at an index
document.write("At Index 2 : ", randStr.charAt(2) + "<br/>");
// Split a string into an array
var randStrArray = randStr.split(" ");
// Trim white space
randStr = randStr.trim();
// Convert to uppercase
document.write(randStr.toUpperCase() + "<br/>");
// Convert to lowercase
document.write(randStr.toLowerCase() + "<br/>");
// Styling with JS
var strToStyle = "Random String";
document.write("Big : ", strToStyle.big(), "<br />");
document.write("Bold : ", strToStyle.bold(), "<br />");
document.write("Font Color : ", strToStyle.fontcolor("blue"), "<br />");
document.write("Font Size : ", strToStyle.fontsize("8em"), "<br />");
document.write("Italics : ", strToStyle.italics(), "<br />");
document.write("Google : ", strToStyle.link("http://google.com"), "<br />");
document.write("Small : ", strToStyle.small(), "<br />");
document.write("Strike : ", strToStyle.strike(), "<br />");
document.write("Sub : ", strToStyle.sub(), "<br />");
document.write("Sup : ", strToStyle.sup(), "<br />");
// ---------- CONDITIONALS ----------
// Relational Operators : == != > < >= <=
// === : Equal value and type
// Logical Operators : && \\ !
var age = 8;
if ((age >= 5) && (age <= 6)){
document.write("Go to Kindergarten<br />");
} else if (age > 18) {
document.write("Go to College<br />");
} else {
document.write("Go to Grade ", age - 5, "<br />");
}
document.write("true || false = ", true || false, "<br />");
document.write("!true = ", ! true, "<br />");
document.write("\"5\" == 5 = ", ("5" == 5), "<br />");
document.write("\"5\" === 5 = ", ("5" === 5), "<br />");
// Switch is used to match a limited number of options
switch(age) {
case 5 :
case 6 :
document.write("Go to Kindergarten<br />");
break;
case 7 :
document.write("Go to 1st Grade<br />");
break;
default :
document.write("Subtract 5 from your age<br />");
}
// Ternary Operator assigns a value based on a condition
// (condition) ? iftrue : ifFalse
var canIVote = (age >= 18) ? true : false;
document.write("Can I Vote : ", canIVote, "<br />");
// ---------- LOOPING ----------
// while loops as long as a condition is true
var i = 1;
while (i <= 10){
document.write(i, ", ");
i++;
}
document.write("<br />");
// do while is used when you must go through the loop at least once
do{
var guess = prompt("Guess a number between 1 and 20");
}while(guess != 15)
alert("You guessed it! 15 was the number");
// for is a self contained looping structure
for(j = 0; j <= 20; j++){
// If j is divisible by 2 then skip back to the top of the loop
if((j % 2) == 0){
continue;
}
// If j is equal to 15 break completely out of the loop
if(j == 15){
break;
}
document.write(j, ", ");
}
document.write("<br />");
var customer = {name : "Bob Thomas", address : "123 Main", balance : 50.50};
// for in cycles through an enumerable properties of an object
for(k in customer){
document.write(customer[k], "<br />");
}
// ---------- ARRAYS ----------
// Arrays have variable sizes and can contain multiple types in JS
var tomSmith = ["Tom Smith", "123 Main", 120.50];
// Access first array item
document.write("1st State : ", tomSmith[0], "<br />");
// Add an item
tomSmith[3] = "tsmith@aol.com";
// Overwrite index 2 and fit everything else after index 2 without
// overwriting (Put 0 for second parameter to not overwrite)
tomSmith.splice(2, 1, "Pittsburgh", "PA");
// Delete the 4th index item
tomSmith.splice(4,1);
// Convert an array into a string (Also use toString())
document.write("Array : ", tomSmith.valueOf(), "<br />");
// Convert an array into a string with separator
document.write("Array : ", tomSmith.join(", "), "<br />");
// Delete an index
delete tomSmith[3];
// Sort an array (reverse() for reverse sort)
// Works for sorting strings
tomSmith.sort();
// Sort numbers
var numbers = [4,3,9,1,20,43];
// Descending sort return y - x
numbers.sort(function(x,y){ return x - y });
document.write("Num Array : ", numbers.toString(), "<br />");
// Combine arrays
var combinedArray = numbers.concat(tomSmith);
// Remove the last item
tomSmith.pop();
// Add items to the end
tomSmith.push("555-1212", "US");
// Deletes the first item
tomSmith.shift();
// Adds item to the first index
tomSmith.unshift("Tom Smith");
for (var i = 0; i < tomSmith.length; i++) {
document.write(tomSmith[i], "<br />");
}
// ---------- FUNCTIONS ----------
// Functions provide code reuse and eliminate repetitive code
// Define a function that checks if a value is in an array
function inArray(arrayToCheck, value){
for(i = 0; i < arrayToCheck.length; i++){
if(arrayToCheck[i] === value){
return true;
}
}
return false;
}
var randArray = [1,2,3,4,5];
document.write("In Array : ", inArray(randArray, 4), "<br />");
// Local variables defined in functions can't be accessed outside of
// the function
function times2(num){
var var2 = 2;
return num * var2;
}
// Causes Error : document.write("Val of var2 : ", var2, "<br />");
// Pass a function as a parameter
function times3(num){
return num * 3;
}
function multiply(func, num){
return func(num);
}
document.write("3 * 15 = ", multiply(times3, 15), "<br />");
// Define a function expression
// We can assign functions to variables, store them in arrays,
// pass them into other functions and return them from functions
var triple = function(num){
return num * 3;
};
document.write("3 * 45 = ", multiply(triple, 45), "<br />");
// Receive variable number of arguments
function getSum(){
var sum = 0;
for(i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
document.write("Sum : ", getSum(1,2,3,4,5), "<br />");
// Return a variable number of values
function times2(theArray){
var newArray = [];
for(i = 0; i < theArray.length; i++){
newArray.push(theArray[i] * 2);
}
return newArray;
}
document.write("Array Doubled : ", times2([1,2,3,4,5]).toString(), "<br />");
// Recursive Function
function factorial(num){
if(num <= 1){
return 1;
} else {
return num * factorial(num - 1);
}
}
document.write("Factorial of 4 : ", factorial(4), "<br />");
// 1st: num = 4 * factorial(3) = 4 * 6 = 24
// 2nd: num = 3 * factorial(2) = 3 * 2 = 6
// 3rd: num = 2 * factorial(1) = 2 * 1 = 2
// ---------- EVENT HANDLING ----------
function openAlert(mess){
alert(mess);
}
// ---------- DATE ----------
// Get a Date object
var curDate = new Date();
document.write("Date : ", curDate.getDate(), "<br />");
document.write("Month : ", curDate.getMonth(), "<br />");
document.write("Day : ", curDate.getDay(), "<br />");
document.write("Year : ", curDate.getFullYear(), "<br />");
document.write("Time : ", curDate.getHours(), ":", curDate.getMinutes(),
":", curDate.getSeconds(), ":", curDate.getMilliseconds(), "<br />");
// Create a Date object for my birthday
var myBD = new Date("December 21, 2015");
var msForBD = myBD.getTime();
var timeNow = curDate.getTime();
var tilMyBD = msForBD - timeNow;
document.write("Days til Birthday : ", tilMyBD / (1000 * 60 * 60 * 24), "<br />");
</script>
<!-- ---------- CHANGING ELEMENTS & EVENT HANDLING ---------- -->
<!-- All the events can be found here http://www.w3schools.com/jsref/dom_obj_event.asp -->
<!-- Open alert on click -->
<a href="JavaScript:void(0)" onClick="alert('Hello');">Say Hello</a><br />
<!-- Call a function on click -->
<a href="JavaScript:void(0)" onClick="openAlert('Hi how are you');">Say Something</a><br />
<!-- Change text color on mouse rollover and roll out-->
<a href="JavaScript:void(0)" onmouseover="this.style.color='red';"
onmouseout="this.style.color='blue';"
ondblclick="this.text='You Double Clicked Me'"
onmousedown="this.text='Don\'t Press So hard'"
onmouseup="this.text='Thank You'">Make me Red</a><br />
<!-- Get value in an input element and open alert on change -->
<input type="text" id="randInput"
onChange="var dataEntered=document.getElementById('randInput').value; alert('User Typed ' + dataEntered);"><br /><br />
<!-- When a user clicks a key provide info on the key clicked -->
<form action="#" id="sampForm">
<input id='charInput' type="text">
<p id="keyData">Key Data Here</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form><br /><br />
<img src="ntt-logo.png" id="logo">
<button id="logoButton">Get Logo</button><br />
<input id='mouseInput' type="text" size="30"><br />
Mouse X: <input type="text" id="mouseX"><br />
Mouse Y: <input type="text" id="mouseY"><br />
<button id="clearInputs">Clear Inputs</button><br />
<script>
function getChar(event) {
// event.which returns the key or mouse button clicked
if (event.which == null) {
// Return the char if not a special character
return String.fromCharCode(event.keyCode); // IE
} else if (event.which!=0 && event.charCode!=0) {
return String.fromCharCode(event.which); // Other Browsers
} else {
return null; // Special Key Clicked
}
}
document.getElementById('charInput').onkeypress = function(event) {
var char = getChar(event || window.event)
if (!char) return false; // Special Key Clicked
document.getElementById('keyData').innerHTML = char + " was clicked";
return true;
}
// Change text when the input gains focus
document.getElementById('charInput').onfocus = function(event) {
document.getElementById('keyData').innerHTML = "Input Gained Focus";
}
// Change text when the input loses focus
document.getElementById('charInput').onblur = function(event) {
document.getElementById('keyData').innerHTML = "Input Lost Focus";
}
// Change text when text is selected
document.getElementById('charInput').onselect = function(event) {
document.getElementById('keyData').innerHTML = "Text Selected";
}
// Add a listener that triggers a function on browser resize
window.addEventListener("resize", browserResized);
function browserResized() {
document.getElementById('keyData').innerHTML = "I've been resized";
}
// Make image invisible on click
document.getElementById('logo').onclick = function(event) {
// Change the class for the image
document.getElementById('logo').className = "hidden";
// Change the input element value
document.getElementById('mouseInput').value = "Clicked on image with button " + event.button;
}
// Make image visible on click
document.getElementById('logoButton').onclick = function(event) {
document.getElementById('logo').className = "show";
}
// Change image src on mouseover
document.getElementById('logo').onmouseover = function(event) {
document.getElementById('logo').src = "ntt-logo-horz.png";
document.getElementById('mouseInput').value = "Mouse Over image";
}
// Change image src back on mouseout
document.getElementById('logo').onmouseout = function(event) {
document.getElementById('logo').src = "ntt-logo.png";
document.getElementById('mouseInput').value = "Mouse Left image";
}
// Get mouse x y coordinates
document.body.onmousemove = function(e) {
e = e || window.event;
// Get pageX, pageY : Mouse position relative to the html doc
var pageX = e.pageX;
var pageY = e.pageY;
if (pageX === undefined) {
// clientX, clientY : Mouse position relative to the browsers viewport
// scrollLeft, scrollTop : Pixels an element is scrolled left or
// from the top
pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
document.getElementById('mouseX').value = pageX;
document.getElementById('mouseY').value = pageY;
};
// Clear all input elements
document.getElementById('clearInputs').onclick = function(event) {
var inputElements = document.getElementsByTagName('input');
for (var i = 0; i < inputElements.length; i++) {
if (inputElements[i].type == "text") {
inputElements[i].value = "";
}
}
}
</script>
<!-- ---------- ELEMENT STYLING ---------- -->
<!-- See all of them here http://www.w3schools.com/jsref/dom_obj_style.asp -->
<div id="sampDiv">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget. Fusce ornare feugiat magna, ut faucibus sapien congue ut. Nunc nec fringilla ex, nec varius nisl. Ut eget laoreet nisi. Aenean quis venenatis mauris, at volutpat ante. Donec sollicitudin lacinia ornare. In quis accumsan ligula, id egestas enim.
</div>
<button id="chgBkColor">Background Color</button>
<button id="chgBkImg">Background Image</button>
<button id="chgBorderStyle">Border Style</button>
<button id="chgBorderWidth">Border Width</button>
<button id="chgBorderColor">Border Color</button>
<script type="text/javascript">
// Change background color
document.getElementById('chgBkColor').onclick = function(event) {
document.getElementById('sampDiv').style.backgroundColor = "#EFDECD";
}
// Change background image
document.getElementById('chgBkImg').onclick = function(event) {
document.getElementById('sampDiv').style.backgroundImage = "url('repeatBkgrnd.png')";
}
// Change border style
document.getElementById('chgBorderStyle').onclick = function(event) {
document.getElementById('sampDiv').style.borderStyle = "solid";
}
// Change border width
document.getElementById('chgBorderWidth').onclick = function(event) {
document.getElementById('sampDiv').style.borderWidth = "thick";
}
// Change border color
document.getElementById('chgBorderColor').onclick = function(event) {
document.getElementById('sampDiv').style.borderColor = "blue";
}
</script>
<!-- ---------- MANIPULATING THE DOM ---------- -->
<div id="sampDiv2"><p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit. Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget. Fusce ornare feugiat magna, ut faucibus sapien congue ut. Nunc nec fringilla ex, nec varius nisl. Ut eget laoreet nisi. Aenean quis venenatis mauris, at volutpat ante. Donec sollicitudin lacinia ornare. In quis accumsan ligula, id egestas enim.</p><p>Lorem ipsum dolor sit amet, <b>consectetur adipiscing</b> elit. Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget. <em>Fusce ornare</em> feugiat magna, ut faucibus sapien congue ut. <b>Nunc nec fringilla</b> ex, nec varius nisl.</p></div>
<img src="ntt-logo.png" id="logo2" alt="NTT Logo" height="180" width="180"><br />
<button id="goToGoogle">Go to Google</button><br />
<button id="forwardPage">Forward Page</button><br />
<button id="backPage">Back Page</button><br />
<button id="reload">Reload Page</button><br />
<script type="text/javascript">
// Get current web page info
document.write("Current URL : ", window.location.href, "<br />");
document.write("Current Host : ", window.location.hostname, "<br />");
document.write("Current Path : ", window.location.pathname, "<br />");
// Change site on button click
document.getElementById('goToGoogle').onclick = function(event) {
window.location.href = "http://google.com";
// OR
// window.location.assign("http://google.com");
}
// Go forward a page on click
document.getElementById('forwardPage').onclick = function(event) {
history.forward();
}
// Go back a page on click
document.getElementById('forwardPage').onclick = function(event) {
history.back();
}
// Use history.go(-2) or history.go(2) to jump multiple pages
// Reload page on button click
document.getElementById('reload').onclick = function(event) {
window.location.reload(true);
}
// You can get all ps and then target them like an array
var pElements = document.getElementsByTagName('p');
pElements[3].style.backgroundColor = "#EFDECD";
// Target the html
document.childNodes[1].style.backgroundColor = "#FAEBD7";
// Change the color of the 1st child in sampDiv2
var sampDiv2 = document.getElementById('sampDiv2');
sampDiv2.childNodes[0].style.backgroundColor = "#F0FFFF";
// Style the 1st child of sampDivs 1st child
sampDiv2.childNodes[0].childNodes[1].style.backgroundColor = "#BFAFB2";
// JavaScript can get confused by text nodes when targeting elements
// Text nodes are whitespace, which nodeType will identify with a 3
// while elements as a 1
// You can eliminate text nodes by deleting whitespace or by using a
// minimizer (lastChild and firstChild may not work)
document.write("Node Type : ", sampDiv2.childNodes[0].childNodes[0].nodeType, "<br />");
document.write("Node Name : ", sampDiv2.childNodes[0].childNodes[0].nodeName, "<br />");
sampDiv2.childNodes[1].childNodes[3].style.backgroundColor = "#BFAFB2";
// Changing element attributes
var nttLogo2 = document.getElementById('logo2');
// Check for attributes
document.write("Logo has alt : ", nttLogo2.hasAttribute("alt"), "<br />");
// Change attribute
nttLogo2.setAttribute("alt", "NTT Logo 2");
// Get attribute
document.write("Logo alt Value : ", nttLogo2.getAttribute("alt"), "<br />");
// Get all attributes and print them
var attribList = document.getElementById('logo2').attributes;
for(i = 0; i < attribList.length; i++){
document.write("Attribute ", i, " : ", attribList[i].nodeName, " : ", attribList[i].nodeValue, "<br />");
}
// Add a p element after setting an attribute and text
var paragraph3 = document.createElement("p");
paragraph3.setAttribute("id", "paragraph3");
paragraph3.innerHTML = "Proin eget turpis eget quam luctus malesuada ut ac nulla.";
sampDiv2.appendChild(paragraph3);
// Insert the element before the 1st child
sampDiv2.insertBefore(paragraph3, sampDiv2.childNodes[0]);
</script>
<!-- ---------- OO JAVASCRIPT ---------- -->
<script type="text/javascript">
// Create a customer object by defining the attributes of John Smith
// The variable is a reference to the object in memory
var cust1 = {
name: "John Smith",
street: "123 Main",
city: "Pittsburgh",
state: "PA",
email: "jsmith@aol.com",
balance: 120.50,
payDownBal: function(amtPaid){
this.balance -= amtPaid;
},
addToBal: function(amtCharged){
this.balance += amtCharged;
}
};
// Retrieve the value for the object
document.write("Customer Name : ", cust1.name, "<br />");
// Change the value for the object
cust1.street = "215 Main St";
document.write("Customer Address : ", cust1.street, "<br />");
// Add a property to cust1
cust1.country = "US";
document.write("Customer Country : ", cust1.country, "<br />");
// Delete a property
delete cust1.country;
// Cycle through all the properties for the object
for (var prop in cust1) {
if (cust1.hasOwnProperty(prop)) {
document.write(prop, "<br />");
}
}
// Check if a property is in an object
document.write("name in cust1 : ", "name" in cust1, "<br />");
// Interact with an object using a function
function getInfo(cust){
return cust1.name + " lives at " + cust1.street + " in " + cust1.city + " " + cust1.state + " email : " + cust1.email + " and has a balance of $" + cust1.balance;
}
document.write(getInfo(cust1), "<br />");
// Call object methods
cust1.payDownBal(20.50);
cust1.addToBal(10.00);
document.write(getInfo(cust1), "<br />");
// Create an object constructor
function Customer(name, street, city, state, email, balance){
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.email = email;
this.balance = balance;
this.payDownBal = function(amtPaid){
this.balance -= amtPaid;
};
this.addToBal = function(amtCharged){
this.balance += amtCharged;
};
}
var cust2 = new Customer("Sally Smith", "234 Main", "Pittsburgh", "PA", "ssmith@aol.com", 0.00);
cust2.addToBal(15.50);
// Define a shared prototype property for all objects
Customer.prototype.isCreditAvail = true;
// We define prototype methods that are shared by every object created
Customer.prototype.toString = function(){
return this.name + " lives at " + this.street + " in " + this.city + " " + this.state + " email : " + this.email + " and has a balance of $" + this.balance.toFixed(2) + " Creditworthy : " + this.isCreditAvail;
};
document.write(cust2.toString());
</script>
<!-- ---------- FORM VALIDATION ---------- -->
<div>
Enter your name:
<!-- When they leave the input send a reference to the input element, and a reference to the hel error span -->
<input id="name" name="name" type="text" size="30" onblur="isTheFieldEmpty(this, document.getElementById('name_help'))" />
<span id="name_help"></span>
<!-- this is the id number for the text box -->
</div>
<div>
Enter your street address:
<input id="street" name="street" type="text" size="30" onblur="isAddressOk(this, document.getElementById('street_help'))" />
<span id="street_help"></span>
</div>
<div>
Enter your city:
<input id="city" name="city" type="text" size="30" onblur="isTheFieldEmpty(this, document.getElementById('city_help'))" />
<span id="city_help"></span>
</div>
<div>
Enter your state code:
<input id="state" name="state" type="text" size="2" onblur="isStateOk(this, document.getElementById('state_help'))" />
<span id="state_help"></span>
</div>
<div>
Enter your phone number:
<input id="phone" name="phone" type="text" size="15"
onblur="isPhoneOk(this, document.getElementById('phone_help'))" />
<span id="phone_help"></span>
</div>
<div>
Enter your email:
<input id="email" name="email" type="text" size="30" onblur="isEmailOk(this, document.getElementById('email_help'))" />
<span id="email_help"></span>
</div>
<script type="text/javascript">
function editNodeText(regex, input, helpId, helpMessage)
{
// See if the info matches the regex that was defined
// If the wrong information was entered, warn them
if (!regex.test(input)) {
if (helpId != null)
// We need to show a warning
// Remove any warnings that may exist
while (helpId.childNodes[0]){
helpId.removeChild(helpId.childNodes[0]);
}
// Add new warning
helpId.appendChild(document.createTextNode(helpMessage));
} else {
// If the right information was entered, clear the help message
if (helpId != null){
// Remove any warnings that may exist
while (helpId.childNodes[0]){
helpId.removeChild(helpId.childNodes[0]);
}
}
}
}
// inputField – ID Number for the html text box
// helpId – ID Number for the child node I want to print a warning in
function isTheFieldEmpty(inputField, helpId) {
// See if the input value contains any text
return editNodeText(/^[A-Za-z\.\' \-]{1,15}\s?[A-Za-z\.\' \-]{1,15}\s?[A-Za-z\.\' \-]{1,15}/, inputField.value, helpId, "Please enter a valid name.");
}
// inputField.value – Value typed in the html text box
function isAddressOk(inputField, helpId) {
return editNodeText(/^[A-Za-z0-9\.\' \-]{5,30}$/, inputField.value, helpId, "Enter a Street (Ex.1234 Main St.)");
}
function isStateOk(inputField, helpId) {
return editNodeText(/^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/, inputField.value, helpId, "Enter a State Code in Uppercase (Ex.NY, PA, CA)");
}
function isPhoneOk(inputField, helpId) {
return editNodeText(/^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$/, inputField.value, helpId, "Enter a Phone Number (Ex.412-828-3000)");
}
function isEmailOk(inputField, helpId) {
return editNodeText(/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/, inputField.value, helpId, "Enter an Email (Ex. derekbanas@newthinktank.com)");
}
</script>
<!-- ---------- EXCEPTION HANDLING ---------- -->
<script type="text/javascript">
// Through exception handling we can catch and manage errors rather then
// crashing by surrounding problem code in a try block and handling it
// in a catch block
var custArray = ["Tom", "Bob", "Sally", "Sue"];
var getCust = function(index){
if(index > custArray.length){
throw new RangeError("Index must be >= 0 and <= " + custArray.length );
} else {
return custArray[index];
}
}
try {
document.write("Customer : ", getCust(5), "<br />");
}
catch(ex){
if (ex instanceof RangeError){
document.write(ex.message + "<br />");
}
}
</script>
</body>
</html>