-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJavaScript Notes
More file actions
1935 lines (1307 loc) · 79.5 KB
/
JavaScript Notes
File metadata and controls
1935 lines (1307 loc) · 79.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
JavaScript Notes
JavaScript is the Client-Side scripting language of the Web. It makes pages dynamic and
interactive.
************************ SOME GENERAL NOTES ************************
JavaScript can be implemented either in an external .js file, which is linked to in the <head>
or <body> of an HTML document, or it can be implemented in the actual <head> and <body> of an
HTML document by using the <script></script> tags. Can put as many scripts in an HTML document
as you want.
It is convention to put all JavaScript functions in the <head> if doing scripting in the actual
HTML document.
Using an external file for JavaScript is usually for when it contains code that will be used by
several different webpages. To use an external JavaScript file just link to it with the
"src" attribute in the <script> element.
<script src="externalJSfile.js"></script>
The Document Object Model (DOM) is the official standard for accessing HTML elements through
JavaScript. You can get HTML elements by doing this in JavaScript:
document.getElementById("theId");
Can change the content of an html element by finding it by ID, then using the
.innerHTML="new content";.
Can also change the styling of an html element in the same way except by using something like
.style.color="new color";.
Javascript is commonly use to make webpages dynamic by manipulating HTML elements, and to
validate user input in forms.
By simply writing out JavaScript code, that code will be executed immediately while the page
loads. If you want to execute code when an event occurs, you need to put code inside a function
and then call the function when an event occurs.
// Comments use this or /* */
************************ OUTPUT ************************
To access an HTML element from JavaScript use the following method:
document.getElementById(id)
Need to give HTML elements id attributes to be able to use this method.
Can change the content of an element by using the .innerHTML="new content" like so:
document.getElementById("id").innerHTML="new content";
The innerHTML variable of an HTML element refers to its content.
To write to the document while it is loading use the document.write() method. Note: do not
use the document.write() method after webpage has finished loading or else it will overwrite
the entire webpage.
document.write("write this to the screen");
Can break up a line of code within a text string by using a backslash.
i.e. document.write("Helllo \
World!");
The alert() function will display an alert on-screen: alert("blah");
************************ VARIABLES, OBJECTS, AND DATA TYPES ************************
Delcare variables with the "var" keyword.
var x, y=40, name="todd";
If you re-declare a variable it will not lost its current value.
Before a variable is initialized its type is undefined.
Data types: String, Number, Boolean, Array, Object, Null, Undefined
JavaScript has dynamic types, which means that the same variable can be redeclared as another
type by setting it to a value of another data type.
JavaScript only has one data type for numbers. The Number data type can be used as float of int.
Numbers can be written in scientific notation like so: var y = 123e5;
The boolean values are true or false.
Arrays:
var myArray = new Array();
myArray[0] = "blah";
myArray[1] = "bloop";
var theArr = new Array("blah", "bloop"); // a condensed declaration of an array
var arr = ["blah", "bloop"]; // a literal declaration of an array
Objects:
Objects are delimited by curly braces, inside of which its properties are defined as
name:value pairs separated by commas, with a semi-colon at the end of the closing curly
brace.
var objName = {
name : "Todd",
age : 30,
id : 845
};
You can use variables from an object in two ways:
blah = objName.name; or blah = objNme["name"];
Undefined and Null:
Undefined is the value of a variable before it is initialized.
Variables can be emptied by setting their value to null.
Declaring a variable as an Object:
When the "new" keyword is used in a variable declaration you are declaring the variable
as an object.
i.e. var name = new String;
var blah = new String("blahbleep");
var x = new Number;
More on Objects:
Almost everything in JavaScript can be an Object: String, Functions, Arrays, Dates...
String objects have built in properties/methods like objName.length and
objName.indexOf("section of the String"), which returns the index where that section of the
string starts. Also .toUpperCase(), and so on.
Can create your own objects like in different ways. Two ways shown here:
var obj = {
bleep : 23,
bloop : "wall-e"
};
or
var obj = new Object();
obj.bleep = 23;
obj.bloop = "wall-e";
Can also add new variables and methods to already existing objects.
Variable Scope:
Variables declared outside of any function are Global in scope, and are available to all
scripts and functions on the webpage, and they are deleted when you close the page.
If you just assign a variable a value without declaring it (without using the "var" keyword)
then that variable is Global in scope, even if it happens inside a function.
i.e. firstName="Todd"; // this is now a global variable
Operators:
Use a "+" between string variables to concatenate them. Can also concatenate a string and a
number using "+", which will result in a string.
"===" the three equal signs means that the values are exactly equal (both in value and data
type). Just two equal signs "==" just means their value is equal and some type conversion
may have taken place to make them equal.
Similarly, "!==" means two values are of different value or different type.
&& - and || - or ! - not
************************ FUNCTIONS ************************
Syntax (Declaration Notation):
function myFunc(var1, var2) {
code...
return blah;
}
OR
Syntax: var myFunc = function(params) {
code...
};
When you create a function in the second way, by assigning a function to a variable, when
the software runs it won't have to load up the function when the program starts, instead it
will only load when the variable that holds the function is used.
Can return a value by either assigning it to a variable, or you can put that value straight
into the content of an HTML element like so:
document.getElementById("theId").innerHTML=myFunc(args);
Can call functions when events happen, like on button clicks. Some examples:
<button onclick="myFunc(args)"> Click Me </button>
<input type="button" value="blah" onclick="myFunc(args)">
Functions in JavaScript are first order objects (I think that's what it's called), which means functions are data too. This allows functions to be sent as arguments to other functions.
Anonymous functions are functions that don't have a name because the functions are defined in-place in argument fields of a function call.
Syntax:
myFunc(var1, function(params) {
// code for anonymous function...
});
The above anonymous function is also an example of a callback function, which is a function that is called after the calling function (myFunc) is finished executing. So in the above example, myFunc() will finish executing and then call the anonymous function from the argument list. This creates asynchronous execution because JavaScript will keep executing other pieces of code while myFunc() is executing, and then the anonymous function is executed once myFunc is finished.
Note that when using the Declaration Notation for creating a function that any function created
this way is conceptually moved to the top of their scope. This means that function declarations are not part of the regular top-to-bottom flow of control. So you can declare a function in this way below a piece of code that uses it. This only works for declaration notation, if you define a function as a variable this does not work - the function variable must be created in the code above where it is used.
Note also that in JavaScript you should never declare a function using declaration notation inside a conditional block or loop. Only use declaration notation to create a function in the outermost block of a function or program.
Optional Arguments:
JavaScript isn't too strict on the number of arguments sent to a function. If you give too many, the extra arguments are ignored. If you give too few, the missing parameters get assigned the value of undefined.
This functionality allows you to make a function take optional arguments, which would just entail having an if-statement in the function that asks if an argument is undefined and if it is then give it some default value. So you could have two parameters, and if the user only gives one parameter then the function definition assigns a default value to the second parameter.
Closure:
Closure is being able to reference a specific instance of local variables in an enclosing function. A function that "closes over" some local variables is called a closure. A closure frees you from having to worry about lifetimes of variables, and also allows for some creative use of function values.
So a closure is a function that is returned by another function, and this closure that is returned includes a local variable from the outer function. In this case the closure keeps the local variable alive even after the outer function is exited. And so if that outer function was called again you would then have two instances of the local variable of that function still in existence out of that function because they exist in the closures.
i.e.
function wrapValue(n) {
var localVar = n;
return function() { return localVar; };
}
var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1()); // outputs: 1
console.log(wrap2()); // outputs: 2
i.e.
function multiplier(factor) {
return function(number) {
return number * factor;
}
}
var twice = multiplier(2);
console.log(twice(5)); // outputs: 10
Note that iteration in JavaScript tends to be faster than recursion. So for simple problems just use iteration. But for more complex problems where iteration would make the code really complex, if recursion simplifies the code a lot then use recursion and just give up some of the speed you lose from recursion.
The general rule of programming is to not worry about efficiency until you know for sure that the program is too slow. If it is, then find the parts you can make more efficient.
Using two sets of parenthesis:
In JavaScript you can use two sets of parenthesis when calling a function if the function has a closure.
************************ CONDITIONALS AND LOOPS ************************
if-statement:
if (blah) {
code...
} else if (blah) {
code...
} else {
code...
}
variableName = (condition) ? valueIfTrue : valueIfFalse;
switch statement:
switch(var) {
case value1:
code...
break;
case value2:
code...
break;
default:
code...
break;
}
for-loop:
for (var i=0; i < blah; i++) {
code...
}
for/in-loop:
Loops through the properties of an object. So not really the same as a for-each.
for (var x in obj) {
code...
}
forEach:
The forEach is a method to use on arrays.
arr.forEach(function(item) {
code for each item of the array...
});
while loop:
while (condition) {
code...
}
do-while loop:
do {
code...
} while (condition);
The "break;" statement jumps out of a loop.
The "continue;" statement jumps to the next iteration of a loop.
JavaScript has labels (reminds me of Assembly Language). To label JavaScript statement just
use this syntax: label:
statements
The break and continue statements can normally only be used inside a loop and a switch or a
loop, respectively. But by using a label and putting a block of code between { } (specifying
the label's block of code) you can use the "break label;" statement to jump out of that block
of code. Continue doesn't work with labels, only break.
i.e.
blah: // the label
{
code...
break blah; // program breaks out of this block here
code...
}
************************ ERRORS - THROW, TRY, AND CATCH ************************
The "try" statement lets you test a block of code for errors.
The "catch" statement lets you handle the error.
The "throw" statement lets you create custom errors.
When an error occurs the JavaScript engine will 'throw' an error.
Syntax:
try {
code to try to execute...
} catch (err) { // the argument will grab the error
handle errors here...
}
Create custom errors by 'throw an exception', by using the throw keyword within a try-catch
block. Like in the try block, if you want to specify a custom error (like incorrect input) you
can do if(blah) throw "bad input"; or something like that. The catch block will
then grab that 'thrown' error in its argument and you can define what you want to do with that
error, like print it to the screen.
************************ VALIDATING FORMS ************************
JavaScript is often used to validate data in HTML forms before sending it off to a server.
Syntax for getting data from an item in a form:
var myVar = document.forms["formName"]["itemName"].value;
Example of getting data from a form:
JS: function validate() {
var myVar = document.forms["formName"]["itemName"].value;
...code to check to validate it...
}
HTML: <form name="formName" action="blah.php" onsubmit="return validate()" method="post">
Name: <input type="text" name="itemName">
<input type="submit" value="Submit">
</form>
Can use JavaScript to check to make sure all required form items have been filled out, use
Regex's to check for correct data in various form items, etc.
************************ OBJECTS ************************
Note:
Also look above in the Variables, Objects, and Data Types section for some stuff on Objects.
Note: JavaScript doesn't use Classes, even though it uses Objects. JavaScript is prototype
based, not class based.
Nearly everything in JavaScript can be used as an object. Booleans, Numbers, Strings, Dates,
Math, Regular Expressions, Arrays, and even Functions are either always objects or can be
treated as either primitive data or objects.
See this: http://phrogz.net/JS/classes/OOPinJS.html for info about creating public and private variables and methods of objects. (var means private, this. means public).
Since functions are objects, you can create an object simply calling a function (with the "new"
keyword) whose arguments act as a constructor and assigning them to values using the "this" keyword, and assigning that new object/function to a variable.
i.e.
function person(fName, lName, age, eyeColor) { // function as object constructor
// variables
this.fName = fName;
this.lName = lName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName=changeName; // using a function as a variable
// methods
function changeName(name) {
this.fName = name;
}
}
var someDude = new person("Jonas", "Simbacca", 55, "gray"); // this creates an object
var someLady = new person("Angie", "Lovelace", 23, "green");
Instead of creating an object constructor as a function you can also just straight up create an object as a variable instead of constructing an object off a constructor blueprint:
i.e.
var obj1 = {
// data...
// methods...
};
There are two ways to make methods of objects during the object definition.
1. Create a member variable to reference the function:
this.funcName = funcName;
function funcName(params) { body }
2. Assign an anonymous function directly to a member variable:
this.funcName = function(params) { body };
You can add properties (variables and methods) to already existing objects.
i.e.
person.hairColor = "blonde";
or
person['hairColor'] = "blonde";
Properties of values can be accessed or created using either dot notation or brackets. If a property name is not a valid variable name (like a string with spaces, or a number) then it can only be accessed through bracket notation.
You can delete a property from an object using the delete keyword.
Syntax:
delete myObj.propName;
The "in" operator, when applied to a string on its left side and an object on its right side, returns a boolean value indicating whether that object has a property of that name (the string).
i.e. This checks if myObj has a property called todd:
"todd" in myObj // returns true if myObj has a todd property
JavaScript's == operator, when comparing objects, will return true only if both objects point to exactly the same value. If two objects hold the same values but don't point to the same spot in memory then == will return false.
************************ DATA STRUCTURES ************************
Data Structures can be made by making an object with just data.
You can make an object with just data (no methods) with a little bit different syntax than the objects shown in the section above. It is similar to the second way shown in the previous section except that instead of using (this.myVar = value) you just use (myVar: value), or if the property name is not a valid variable name (like numbers or text with spaces) you can just put it in quotes like you normally would in such situations. And you separate the properties in the data structure object with commas. And don't forget to put a semi-colon after the object definition, just like when you declare any object directly as a variable.
i.e.
var dataStructObj = { // { } creates an object
myVar: true,
myArr: ["yo", "man", 56],
"my string": "Me llamo Todd",
"3": false
};
************************ NUMBERS ************************
JavaScript Numbers data type are 64-bit floats.
Can use Octal numbers by putting a 0 in front of the number, i.e. 0475
Can use Hexadecimal numbers by putting a 0x in front of the number, i.e. 0x4D
Can display numbers in different bases using the .toString() method and sending as the
argument the base you want to display the number in.
If you calculate a number outside the range of the 64-bit float JavaScript will return the value
of Infinity or -Infinity. Division by zero also generates +/-Infinity.
NaN is a reserved word in JavaScript to indicate the result of a numeric operation is not a
number. can use the isNaN(myVar) method to test whether a result is a number or not. Infinity
counts as a number.
Numbers can be primitive number data type or objects (var x = new Number(123);).
Can use typeof(var) function to check the data type of the var.
Properties of the Number wrapper object:
Number.MAX_VALUE
Number.MIN_VALUE
Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY
Number.NaN
Number.prototype
Number.constructor
Methods of the Number wrapper object:
Number.toExponential()
Number.toFixed()
Number.toPrecision()
Number.toString()
Number.valueOf()
All methods of the Number object are available to primitive values because JavaScript will
temporarily transfer primitive values to objects before executing the methods.
************************ STRINGS ************************
Can use single quotes or double quotes for strings.
Can access each character in a string using its index: myString[index];
Member variables of Strings:
.length
.prototype
.constructor
Methods of Strings:
.indexOf("substring") // returns -1 if substring is not found
.match("substring") // if finds substring returns the substring, if not returns null
.replace("original substring", "new substring");
.toUpperCase()
.toLowerCase()
.split("delimter") // converts a string to an array
.charAt()
.charCodeAt()
.concat()
.fromCharCode()
.lastIndexOf()
.localeCompare()
.search()
.slice()
.substr()
.substring()
.trim()
.valueOf()
.toString()
Use \ for escape characters.
Strings can be primitive strings or objects.
String variables are immutable, they cannot be changed.
************************ DATES ************************
The Date object is used to work with dates and times.
Four ways to initiate a Date object:
new Date() // current time and date
new Date(milliseconds) // milliseconds since 1/1/1970
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Some of the parameters are optional.
To set a date:
myDate.setFullYear(2010, 0, 13) // sets myDate to Jan. 13th, 2010
myDate.setDate(myDate.getDate()+5); // add days to the date
Can compare two days with a simple comparison operator.
************************ ARRAYS ************************
Can have variables of any type, or any type of object, in a single array.
.length gives the number of elements in the array.
.indexOf(element) gives the index position of that argument
Can create new array methods using Prototype. Prototype is a global constructor in JavaScript
and it can construct new properties and methods for any JavaScript object.
i.e.
Array.prototype.ucase=function() {
for (i=0; i<this.length; i++)
this[i] = this[i].toUpperCase();
}
Some methods for arrays:
.push(elements); // appends one or more elements onto an array
.pop(); // removes and returns the last element of the array
.join(delimiter); // Joins the elements into a string separated by the delimiter
************************ MATH OBJECT ************************
The JavaScript math object allows you to perform mathematical tasks.
See the following webpage for all the constants and methods that can be used through the
Math object:
http://www.w3schools.com/jsref/jsref_obj_math.asp
************************ REGULAR EXPRESSIONS ************************
Syntax:
var pattern = new RegExp(pattern, modifiers);
or var pattern = /pattern/modifiers;
Modifiers are used to perform case-insensitive and global searches.
"i" modifier is used to perform case-insensitive matching
"g" modifier performs a global match (find all matches instead of stopping after the first)
"m" modifier performs multi-line matching
Note: below in examples "pattern" means its a regex object.
test()
The test() method searches a string for a specified value, and returns true or false.
i.e. pattern.test(str);
exec()
The exec() method searches a string for a specified value, and returns the text of the
value found. If not match is found, it returns null.
i.e. pattern.exec(str);
match()
The match() method searches a string for a match against a regular expression given to
it as the argument, and returns the matches as an Array, or null if no match.
i.e. str.match(/pattern/modifiers);
Use this website to see specifics on how to make regexs:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
************************ DOCUMENT OBJECT MODEL (DOM) ************************
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
When a webpage is loaded, the browser creates a DOM of the page, which is constructed as a
tree of Objects. The DOM is an interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document. Basically, DOM is a standard for
getting, changing, adding, and deleting HTML elements.
It defines HTML elements as objects, the properties of all HTML elements, the methods to
access all HTML elements, and the events for all HTML elements.
DOM Tree of Objects example:
Document
|
Root Element <html>
_________________________|____________________________
| |
Element <head> Element <body>
| ___________|__________
Element <title> | |
| Attribute "href" ----- Element <a> Element <h1>
Text: "My title" | |
Text: "My link" Text: "My Header"
With the DOM, JavaScript can do all these things:
change all HTML elements
chagne all HTML attributes
change all CSS styles
remove existing HTML elements and attributes
add new HTML elements and attributes
react to all existing HTML events
create new HTML events
The DOM standard is separated into three parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
--------------------
DOM Methods and Properties
HTML DOM methods are actions you can perform on HTML elements.
HTML DOM properties are values of HTML elements you can set or change.
In the DOM programming interface, all HTML elements are defined as objects.
.getElementById("id") // method to access and HTML element by its id attribute
.innerHTML // property that holds the content of an HTML element
--------------------
DOM Document
In the DOM, the document represents the webpage. It is the owner of all other objects in
the webpage. To access anything you always start by accessing the document object:
Syntax: document.
Finding HTML Elements:
document.getElementById("id")
document.getElementsByTagName("tagname")
document.getElementsByClassName("classname")
document.forms[] // finding elements by HTML element objects
Changing HTML Elements:
document.write(text) // write into the HTML output stream
document.getElementById(id).innerHTML= // change the content of an HTML element
document.getElementById(id).attribute= // change the attribute of an HTML element
document.getElementById(id).style.attribute= // change the style of an HTML element
Adding and Deleting HTML Elements:
document.createElement()
document.removeChild()
document.appendChild()
document.replaceChild()
Adding Event Handlers:
document.getElementById(id).onclick=function() { code... }
--------------------
DOM Elements
var x = document.getElementById(id); // find an HTML element, if not found x = null
var x = document.getElementBYId(id);
var y = x.getElementsByTagName(HTML tag); // puts all of those tag elements inside the
// element with the id into an array, y
var x = document.getElementsByClassName(class); // x gets an array of all elements
// with that class name
Finding HTML Elements by HTML Object Collections:
Examples of HTML object collections are:
document.forms, document.anchors, document.images, document.links
The following code gets an HTML form, puts it in x, then loops through the elements
of that form, placing the value of each form element in a string.
var x = document.getElementById(someForm);
var txt = "";
for (var i=0; i<x.length; i++)
txt = txt + x.elements[i].value + "<br>";
--------------------
HTML DOM
Can change the contents of HTML elements (already shown above).
Can change the value of an attribute in an HTML element.
document.getElementById("someImage").src="newImage.jpg";
--------------------
DOM Changing CSS
document.getElementById("someID").style.color="blue";
Using an event to make a change, like a button click:
<button type="button" onclick="document.getElementById('someId').style.color='red'">
Click Me </button>
--------------------
DOM Events
To execute code when a use clicks on an element, add JavaScript code to the HTML onclick
attribute: onclick=JavaScript
Examples of HTML Events:
-user clicks the mouse
-a web page has loaded
-an image has been loaded
-mouse moves over an element
-input field is changed
-a form is submitted
-user strokes a key
Examples:
<h1 onclick="this.innerHTML='blah'"> Click this text </h1>
<h1 onclick="myFunc(this)"> Click this </h1> // "this" arg is the element id
<button onclick="displayDate()"> Click this Button </button>
function displayDate() { document.getElementById("demo").innerHTML=Date(); }
<p id="demo"></p>
document.getElementById(id).onclick=function(){displayDate()} // note: have to put
// function() {funcName()} for this
// to work
Onload and Onunload Events:
The onload and onunload events are triggered when the user enters or leaves the webpage.
The onload event can be used to check the visitor's browser type and browser version. These
two events can be used to deal with cookies.
i.e. <body onload="checkCookies()"> // checkCookies() is a custom function
Onchange Event:
Often used in combination with validation of input fields. This will perform some function's
actions when an input element has been changed (after it has been clicked off of or Enter
is pressed).
i.e. <input type="text" id="fname" onchange="myFunc()">
Onmouseover and Onmouseout Events:
Can be used to trigger a function when the user moves the mouse over, or out of, an element.
i.e. <div onmouseover="myFunc(this)" onmouseout="myOtherFunc(this)"> blah </div>
Onmousedown, Onmouseup, and Onclick Events:
These events are all part of a mouse-click. onmousedown event is triggered when mouse button
is pressed down, onmouseup is triggered when mouse button is released, and finally onclick
is triggered when the mouse-click is completed.
Onfocus Event:
Event can call a trigger when an element, like an input field, gets focus.
i.e. <input type="text" onfocus="myFunc(this)">
--------------------
DOM Navigation
With the DOM you can navigate the node tree using node relationships.
The entire document is a document node.
Every HTML element is an element node.
The text inside HTML elements are text nodes.
Every HTML attribute is an attribute node.
All comments are comment nodes.
You can access all of these using JavaScript.
New nodes can be created, and all nodes can be modified or deleted.
The terms parent, child, and sibling are used to describe the hierarchial relationship of
the nodes. <html> is the root node, it is the parent to its children, who are siblings -
the <head> and <body>, the <head> being the firstChild, the <body> being the lastChild.
This hierarchy goes along all the way though the HTML document.
Use the following properties in JavaScript to navigate between the nodes:
.parentNode
.childNodes[nodeNumber]
.firstChild
.lastChild
.nextSibling
.previousSibling
Use this to get the value of, for instance, text node: .nodeValue
-nodeValue for element nodes is undefined
-nodeValue for text nodes is the text itself
-nodevalue for attribute nodes is the attribute value
Use this to get the name of a node: .nodeName
-nodeName is read-only
-nodeName of an element node is the same as the tag name
-nodeName of an attribute node is the attribute name
-nodeName of a text node is always #text
-nodeName of the document node is always #document
Use this to get the type of a node: .nodeType
The most important types are:
Element - NodeType = 1
Attribute - NodeType = 2
Text - NodeType = 3
Comment - NodeType = 8
Document - NodeType = 9
Two special properties that allow access to the full document:
document.documentElement - the full document
document.body - the body of the document (contains the source code of
the body)
--------------------
DOM Elements (Nodes)
Creating new HTML elements/nodes (must append the new element to an existing one as its
last child node):
var parag = document.creatElement("p"); // create a new <p> element
var node = document.createTextNode("This is new"); // create new text node
parag.appendChild(node); // gives <p> text(new text node)
var element = document.getElementById(existingNode); // finds an existing element
element.appendChild(parag); // adds new <p> to existing one
Creating new HTML element with insertBefore(), instead of appending the new node as the
last child of an existing node you can insert it into the list of the existing nodes
children before some specified node:
var parag = document.createElement("p");
var node = document.createTextNode("This is new.");
parag.appendChild(node);
var element = document.getElementById("someID");
var child = document.getElementById("otherID");
element.insertBefore(parag,child); // inserts parag node before child node
Remove existing HTML elements:
var parent = document.getElementById("someID");
var child = document.getElementById("otherID");
parent.removeChild(child);
Replacing HTML elements:
var parag = document.createElement("p");
var node = document.createTextNode("This is new.");
parag.appendChild(node);
var parent = document.getElementById("someID");
var child = document.getElementById("otherID");
parent.replaceChild(parag, child); // replaces child node with parag node
--------------------
DOM Node List
A node list is an array of nodes.
The getElementsByTagName() method returns a node list.
i.e.
var x = document.getElementsByTagName("p"); // x becomes an array of all <p>'s
x[0].innerHTML; // gives access to the contents of the first node in the node list
x.length; // gives access to the length of the node list
************************ BROWSER OBJECT MODEL (BOM) ************************
There is no BOM standard, so they methods and properties may vary a little between the browsers.
The Window Object
Supported by all browsers. Represents the browser's window. All global JavaScript objects,
functions, and varaiables are members of the window object, including the document object.
window.document.getElementById("blah"); is the same as document.getElementById("blah");
Window Size:
The window size is the browser viewport, not including toolbars and scrollbars - so the
actual size of where the web content displays.
For most browsers:
window.innerHeight - the inner height of the browser window
window.innerWidth - the inner width of the browser window
For IE 5,6,7,8:
document.documentElement.clientHeight
document.documentElement.clientWidth
or
document.body.clientHeight
document.body.clientWidth
A solution for covering all browsers is in this example:
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
Other window methods:
window.open() - opens a new window
window.close() - close the current window
window.moveTo() - move the current window
window.resizeTo() - resize the current window
Properties of the Window object, shown below, don't need the window prefix when using them.
--------------------
The Window Screen Object
window.screen contains info about the user's screen.
window.screen can be written without the window prefix, so just: screen
screen.availWidth - available screen width.
returns the width of the user's screen in pixels, minus
interface features like the windows taskbar.
screen.availHeight - available screen height.
returns the height of the user's screen in pixels, minus
interface features like the windows taskbar.