-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJAVASCRIPT.txt
1794 lines (1560 loc) · 69.6 KB
/
JAVASCRIPT.txt
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
###########
### TOC ###
###########
#> OPERATOR, INPUT, OUTPUT
#> STRING
#> ARRAY
#> CONTROL STRUCTURE AND ITERATION
#> FUNCTION
#> OBJECT
#> CONSTRUCTOR, CLASS
#> OBJECT ORIENTATION - 4 PILLARS OOP
#> DOCUMENT, QUERYSELECTOR, EVENTLISTENER
#> CSS VARIABLE HANDLING
#> API ACCESS
#> JQUERY
#> DATE
#> MATH
#> LOCAL STORAGE
#> MODULE EXPORTS
#> ASYNCHRONOUS HANDLING
#> REQUESTS
#> NODE.JS
#> REACT
#> TOOLS OVERVIEW
#> EXAMPLE FULL STACK
#> AZURE AUTHENTICATION
#> PKG (create executable from node.js)
#> HEROKU (hosting web-apps, running scripts in the cloud)
#> NODEMAILER (send mails)
###### OPERATOR, INPUT, OUTPUT
// Comment something => Comments in Javascript
/*Text xzy*/ => Multiline comments
let intStr = "7" => Declare and assign string (possible with "" or '') - "var" was the earlier version in the past for that
"/n /t" => Linebreak and Tab should not used - is morely css-stuff for formating
let age = 24 => Declare a variable and assign int (also signed int like -36)
let var => Defining without assigning (var gets value undefined)
let var, age = 25 => Define 2 variables (one without value and one with value)
let [a, b, c] = [5, 8, 12] => Define and assign 3 variables (a=5, b=8, c=12)
const age = 25 => Declare a constant and assign int (constant can not be changed like variables)
let float = 5.14876 => Declare and assign float (also signed float like +4.5763
let intNum = parseInt(intStr,10); => Change String to Int with base 10
let floatStr = "5.14673" => Declare and assign string
let floatNum = parseFloat(floatStr); => Change String to Float
let v = user || "guest" => Defines+Assigns a variable (if user exists/has a value use that - otherwise initialize with "guest"
const inp = prompt("Enter:") => Open windows for entering something and store in const inp
num.toString() => Convert numeric value to string
num + "" => 2nd method to convert numeric value to string
String(n) => 3rd method to convert number / int to a String
Number(s) => Converts String to Number / Int
typeof (x) => Shows the type of the variable as string (eg. "number", "string", "boolean")
7 % 2 => Modulo / Rest of the division (=> 1)
x == y => Check 2 values / variables (result in true / false)
x === y => Equal value and equal type
x != y => Not equal
x !== y => Not equal value and not equal type
>,<,>=,<= => Greater, lesser, greater + equal , lesser + equal
isNaN(x) => Check if value is NaN (NotANumber) - eg. when converting with Number() and the value is no number
Number.isInteger(n) => Check if n is a integer
num++; => Makes variable +1
console.log(num) => Outputs variable num in console
console.table(object) => Outputs element as table (eg. for objects, arrays)
alert("Text!") => Alert information in a window
alert(`Bla ${name} bla`) => Alert some text with outputing the variable "name" between (using backticks "`"
n = n.toFixed(2) => Round to 2 decimal digits
[x, y] = [y, x] => Swap 2 variables
process.exit(1) => Exit javascript node program
###### STRING
let s = "this is a test" => Define a string
let s = "this \n text" => String with linebreak \n
s.slice(0,1) => extract only the first character
s.slice(-1) => last char of a string
s.slice[3,5] => slicing 2 chars from pos 3 and 4
s.slice[3] => slice from pos 3 to the end
s.length => shows the length of the string
s = s.toLowerCase() => Lowercase the whole string
s = s.toUpperCase() => Uppercase the whole string
s.charAt(1) => Returns the second char of a string
s.search("xyz") => Search if "xyz" is int the string - returns the position where found - when not found returns -1
s.includes("ee") => Check if string/chars are in
sNew = s.replaceAll("abc","xyy) => Replace "abc" with "xyz" for any occurrences in the string (only working for new browsers!)
sNew = s.replace(/abc/g,"xyz") => 2nd method for replacing everything (works for more browsers!)
sNew = s1.concat(s2) => Concatenate 2 strings
s.trim() => Delete all whitespaces at the beginning and the end
s.repeat(3) => Repeat string 3 times
s.split(" ") => Split the words in a array
s.trim() => Delete all whitespaces at the beginning and the end
s.padstart(3,"0") => Fills leading zero in a string with allways 3 chars - eg. 006
s.indexOf("ee") => Find Index of first occurence of this string
s.charAt(1) => Outputs the x character in the string => second char of the string (same as s[1])
s.slice(-3) => Get the last 3 chars of the string
s.substr(s.length-3) => 2nd variant: Get the last 3 chars of the string
s.charCodeAt(0) => Return Ascii-Code of the first character of the string
s.endsWith("?") => Returns True if the string end with "?"
char = String.fromCharCode(65) => Returns char for specific ascii-code
char.match(/[A-Z]i) => Check if char is in A-Z
[...s] => Spread-Operator for string (=> build array with each character)
s = JSON.stringify(obj) => Convert object-element to string
calcDate.toISOString().split('T')[0] => Convert datetime-object to string in format "yyyy-mm-dd"
###### ARRAY
let arr = []; => Define an array
let arr = [6,7,8]; => Define an array and initialize it
let mat= [[1,2,3],[4,5,6],[7,8,9]] => Define multidim array
arr[1] => Get second element => 7
arr[arr.length-1] => Access last element in array
mat[1][1] => Get element in the matrix => 5
arr[2] = 9 => Replace the third element
String(Arr) => Returns list as a string => "6,7,8"
a1 === a2 => Must allways be compared with triple = (only == would be wrong)
arr.length => Total count of the elemets in the array
arr.pop() => Extracts and delete element at the end (fast!)
arr.shift() => Extracts and delete element at the begin (slow!)
arr.push("X","Y") => Append new elements to the array at the end (fast!)
arr.unshift("Y","Z") => Add new elements to the array at the beginning (slow!)
ergArr = arr.slice(2,3) => Copy elements from index 2 to index 3 => result is one char at index 2
ergArr = arr.slice(-2) => Copy the last 2 elements of the array
arr.splice(2,1) => Delete 1 element beginning from index 2
arr.splice(0,2,10,11) => Delete 2 elements beginning from the index 0 - and insert the elements 10 and 11
arr.splice(-1,0,3,4) => From index -1 delete 0 elements and add 3 and 4
ergArr = arr.splice(0,2) => Delete 2 elements beginning from the index 0 - and assign them to ergArr
arr.every(x => x > 0) => Return true if all elements are bigger than 0
ergArr = arr1.concat(arr2) => Concatenate 2 arrays to one
arr.indexOf("xyz") => Returns first index position of element "xyz" (if not exists result is -1)
arr.lastIndexOf("xyz") => Return the last index position of the element "xyz"
arr.includes("xyz") => Check if string exists in the array
arr.reverse() => Reverse the entire array
arr = varStr.split(" ") => Split the words in a array
varStr = arr.join(", ") => Join the elements from the array in a string with ", " as seperator
Array.isArray(arr) => Check if object is an array (if array = true)
for (let i=0; i < arr.lenth; i++) {do smth.} => Iterate through index of the array
for (let elem of arr) {alert(arr)} => Iterate through array elements
arr=Array.from(document.querySelectorAll("a")) => Convert a node-list to an array
arr=[...document.querySelectorAll("a")] => 2nd method for converting node-list to an array
arr.join(" ") => Concatenate the array to a string seperated by " "
arr.sort((a,b) => a > b ? 1 : -1) => Order array ascending
arr.sort((a,b) => a > b ? -1 : 1) => Order array descending
arr.sort(function(a,b) {return a > b ? 1 : -1} => Ordering long method with function
Math.max(...arr) => Find max value in an array with spread operator
Math.min(...arr) => Find min value in an array with spread operator
let [a,b] = ["Ha","Ho","Hi","He"] => Array Destrucuring Expl1 (a will be "Ha" and b will be "Ho"
let [a,,,d] = ["Ha","Ho","Hi","He"] => Array Destrucuring Expl2 (a will be "Ha" and d will be "He"
let [a,...rest] = ["Ha","Ho","Hi","He"] => Array Destrucuring Expl3 (a will be "Ha" and rest will be ["Ho","Hi","He"]
[a,b] = [b,a] => Swapping values (a will be b and b will be a)
=> Iterate trough array by index and element (with shortform)<br>
=> Outputs index and Outputs element of array
=> (return is not working here - forEach loops are allways running for all elements)
""
arr.forEach((elem,idx) => {
console.log(idx)
console.log(elem)
})
""
=> Iterate through array by elements and index (with longform)<br>
=> Outputs index and Outputs element of array
=> (return is not working here - forEach loops are allways running for all elements)
""
arr.forEach(function(elem,idx) {
console.log(idx)
console.log(elem)
})
""
=> Iterate trough an array with 1sec pause at every element
""
names.forEach((name, i) => {
setTimeout(() => {
display(name);
}, i * 1000);
});
""
=> Map Method - Short Method (Maps a functionality to all elements of the array - every element multiplicated by 2)
""
let newarr = arr.map(x => x * 2);
""
=> Map Method - Long Method (for more code)
""
let newarr = arr.map (function(x) {
x = x * 2
}
""
=> Filter Method - Long Method (Filters all values which are > 6 eg. in a new array)
""
let newarr = arr.filter (function(x){
if (x > 6) {
return true
}
})
""
=> Filter Method - Short Method in one line
""
let newarr = arr.filter(x => x > 6);
""
=> Reduce Method - for doing something with the array and output / calculate something
=> "total" is the new calculation element - result of this is the sum of all elements of the array
=> every element is added to total - 0 is the default value of "total"
""
erg = arr.reduce ((total, elem) => {
return total + elem
},0)
""
=> FindIndex Method - find the index-location of an element in the array (if nothing is found it returns -1)
""
let idx = arr.findIndex(x => {
return x < 10;
})
""
=> Some Method - checks whether at least one element in the array passes the test - returns boolean answer
=> 1st line defines the check function - 2nd line checks the array with the function
""
const even = (element) => element % 2 === 0;
arr.some(even)
""
=> Every Method - checks whether all elements in the array passed the test by the defined function - return boolean answer
=> 1st line defines the check function - 2nd line checks the array with the function
""
const isLower = (elem) => elem < 40;
arr.every(isLower)
""
=> example for a setTimeout
=> the first and second message will appear immediately - the middle message only after 2 seconds
""
console.log('First message!');
setTimeout(() => {
console.log('This message will always run last...');
}, 2000);
console.log('Second message!');
""
###### CONTROL STRUCTURE AND ITERATION
If condition with else if and else
""
if (condition is true) {
=>Do something
}else if (condition is true){
=>Do something else
}else{
=>Default else
}
""
if (a == 9) && (b == 7) { c = "Hurra!" } => If structure with logical and
if (a == 9) || (b == 7) { c = "Hurra!" } => If structure with logical or
if !(a > 13) => If structure with logical not
Switch Expression
""
switch (expression) { // Switch expression for multiple options
case value1: case value 4 // Do something when expression is value1 or value4
// Do something
break; // Break necessary for any case / value
case value2: // Do something when expression is value2
// Do something
break;
default: // When no case is mathing - then do this
=> Do something
break;
}
""
for (let i=1; i<=5; i++) {} => Iteration from 1 to 5 with for-loop
for (let i=3; i>=0; i--) {} => Iteration backwards from 3 to 0 with for-loop
for (let i=0; i<arr.length; i++) {} => Iterate through an array
for (let char of text) {} => Iterate through a string
for (let key in obj) {} => Iterate through the keys of an object
=> For loop with pause at any iteration
""
for (let i = 0; i < 5; i++) {
setTimeout(() => { // Pause at any iteration for 5 seconds / 5000 ms
console.log("hey");
}, i * 5000);
}
""
=> While loop with break condition
""
while (x < 4) {
if xyz === "abc" {break}
}
""
do {} while (x < 4) => Do While loop with break condition
while (true) {} => Endless while loop - has to be exited somewhere
=> Iterate through array by elements (x)
""
arr.forEach((x) => {
console.log(x)
})
""
0,"",'',null,undefined,NaN => Are all falsy values - can checked with if (xyz)...
isNight ? s="Night" : s="Day" => Ternary Operator for if - if isNight=true then s=Night - else s=Day
###### FUNCTION
=> Normal Function Decleration
""
function addFunc(x=0,y=0) { // Define a function - with default value 0 if no input is given
let erg = x+y // Calculate erg
return erg} // Return erg value
addFunc(3,5) // Function Call
""
=> Function Expression (used for anonymous functions)
""
const add = function(x,y) {...} // Define a function expression (function is assigned to an variable
add(3,5) // Function Call
""
=> Anonymous Function with Fat Arrow syntax
""
const add = (x,y) => {...}
add(3,5) // Function Call
let h = a => a % 3 // Even shorter without parentees
""
=> return-statement with "?" or "||"
""
return (age > 18) ? true : console.log('Did parents allow'); // When age > 18 returns true - otherwise output something in the console
return (age > 18) || console.log('Did parents allow'); // Same logic with "||"
""
=> Use Rest Parameters to accept any number of arguments
""
function max(...numbers) { // Any numbers of arguments
=> do something with a loop
}
""
=> AddEventListener with parameters in the function
""
document.querySelector("#dayToday").addEventListener("click",function() { // define addEventListener as normal but use "function ()"
toggleBackground("today", 6) // call the function with parameters inside
}, false);
""
###### OBJECT
=> properties = attributes of the object (eg. color, shape, minutes, seconds)<br>
methods = functions of the object (eg. start/stop on a stopclock)<br>
everything in javascript is an object (with properties / methods)<br>
eg. arr.length is a property of the object array<br>
eg. arr.pop() is a method of the object array<br>
let obj = {} => Define an object (literal syntax)
let obj = new Object() => 2nd method to define object (construtor syntax)
=> Define an object and initialize it
""
let obj = {
name: "John",
age: 30, // last "," i allowed and called trailing / hanging (its easier so to add/remove/move properties of the object)
shout() { // Defines a method for the object
return "Hurra!"
}
}
""
obj.name => Access property / shows value of the key "name" (1st method) => John (dot.notation)
obj["name"] => Shows value of the key "name" (2nd method) => John (bracket notation)
obj.age => Shows key "age" of the object => 30 (dot notation)
obj.newOne = "xyz" => Add a new propertie to the object
obj.newMethod = function(var) {...do someth...} => Add a new method to the object
obj.newMethod(25) => Call the new method
age in obj => Check if key is in the object
delete obj.age => Delete a property of an object (dot notation)
delete obj["age nr"] => Delete a property of an object (bracket notation)
if ("property" in obj) {...} => Check if a property / method is in an object
arr = Object.keys(obj) => Read the keys of an object into an array
arr = Object.values(obj) => Read the values of an object into an array
arr = Object.entries(obj) => Read alle key / value pairs of an object into an (nested) array
obj.hasOwnProperty("xyz") => Check if xyz i part of the object
Object.keys(obj).length === 0 && obj.constructor === Object => Check if Object is empty
=> Iterate through the keys of the object and outputs key and value
""
for (let key in obj) {
console.log(key, obj[key]
}
""
=> Other example for an object
=> teacher count must have quotations cause it contains a space character
""
var school = {
name: 'The Starter League',
location: 'Merchandise Mart',
"teacher count": 10
students: 120,
teachers: ['Jeff', 'Raghu', 'Carolyn', 'Shay']
};
""
=> 4 Pillars of Object Orientation
- Abstraction = hide everything internally what is not usable for the user of the object
- Encapsulation = very object should be independent and not dependencies outside
- Inheritance = objects can take the properties of existing objects
- Polymorphism = redefine methods for derived classes (object can behave in different ways)
###### CONSTRUCTOR, CLASS
=> Make a Object with the old method
""
function MakeCar (carMake,carModel,carColor){ // Define the constructor function
this.make = carMake, // Define properties for the constructor
this.carModel = carModel, // "this" is referencing to the actual object
this.carColor = carColor,
this.honk = function(){ // Define a mtehod for the constructor
alert(`BEEP ${this.carModel} BEEP`) // Alert something when the method is called (with prop this.carModel)
}
}
let car1 = new MakeCar("Honda","Civic","black") // Create a new car1 (with codeword "new")
let car2 = new MakeCar("Tesla","Roadster","red") // Create a new car1
""
=> Make a Object with the shorthand
""
let robotFactory = (model, mobile) => { // Define constructor with two parameters
return {
model: model, // property1
mobile: mobile, // property2
beep(){ // method
console.log("Beep Boop")
}
}
}
""
=> Make a Object with the new class method (longhand)
""
class MakeCar{ // Define the classs
constructor (carMake,carModel,carColor){ // Define properties for the class
this.make = carMake // Assign the properties of the class to the concrete individual object
this._carModel = carModel // "this" is referencing to the actual object (use "_" to indicate that this properties should only changed with getters)
this.carColor = carColor
}
honk(){ // Define a method for the class
alert("BEEP ${this.carModel} BEEP") // Alert something when the method is called (with prop this.carModel)
}
}
let car1 = new MakeCar("Honda","Civic","black") // Create a new car1 (with codeword "new")
let car2 = new MakeCar("Tesla","Roadster","red") // Create a new car1
""
=> Give new property and function
""
MakeCar.prototype.wash = true // Give all the created cars from the class "MakeCar" a new property "wash"
MakeCar.prototype.newFunc = function () { // Give all the created cars from the class "MakeCar" a new function "newFunc"
console.log("We have a new function!"
}
""
=> Define a getter in the class (returns the name-property of the class-element
=> So when somebody is requesting for obj.name - the return will be for _name
=> When somebody is changing with obj.name = "xzy" - nothing happens, cause the property is named _name
=> Of course with obj._name there would be a change possible - but this is very bad practice cause due the "_" the variable should not be touched
""
get name() {
return this._name;
}
""
=> Inherit a class from another class
=> The class Cat inherits from the class Animal with the keyword "extends"
=> With super - the attributes name and age will be taken / inherit from the class Animal
""
class Animal {
constructor(name, age){
this.name = name
this.age = age
}
speak() {
console.log("Blablabla")
}
}
class Cat extends Animal {
constructor(name, age, usesLitter) {
super(name, age);
this._usesLitter = usesLitter;
}
}
""
=> Define static function - this can only be done for the class itself (or for the instances of the class)
""
static generateName() {...}
""
###### OBJECT ORIENTATION - 4 PILLARS OOP
=> 4 pillars of object orientation in practice
class Animal { // ENCAPSULATION - storing properties and methods together in one object
constructor(name) { // (made it easier to add new stuff / easier to read)
this._name = name // ABSTRACTION - name of the object will be set to _name (so hidden)
}
get name() { // using a getter to return when somebody wants the name with obj.name
return this._name
}
speak() {
console.log(`${this._name} makes a sound`)
}
}
class Dog extends Animal { // INHERITANCE - make class from another class (share parent properties / methods)
constructor(name, breed) { // (helps to elimante redundant code)
super(name) // grabs / inherits the "this._name = name" from the class Animal
this._breed = breed // abstract the breed with _breed (could / should not be touched from anybody)
}
get breed() {
return this_breed
}
speak() {
super.speak() // grab the speak method from the parent class Animal
console.log(`${this._name} barks`) // get an additonal output (so one line from the parent class and one individual)
}
}
class Cat extends Animal {
constructor(name, breed) {
super(name)
this._breed = breed
}
get breed(){
return this._breed
}
speak() {
super.speak()
console.log(`${this.name} meows`)
}
}
let simba = new Dog("Simba", "Shepard")
let machi = new Dog("The Machine", "Pitbull")
let salem = new Cat("Salem", "American Shorthair")
let farm = [simba,machi,salem]
for (a of farm) { // POLYMORPHISM code written to use interface (eg. speak-function) and
a.speak() // knows how to use it at different objects (eg. barks or meows)
} // (helps to avoid if/else and switch cases)
###### DOCUMENT, QUERYSELECTOR, EVENTLISTENER
=> Add Eventlistener
""
document.querySelector('#check').addEventListener('click',func1) // New Method / create an Event Listener / execute function "func1" when mouse is clicked
...'onmouseenter'... // New Method / create an Event Listener / exceute function "func2" when mouse-cursor is over the element
...'input'... // Event Listener with trigger input
...'change'... // Event Listener with trigger every change in the element
...'mousemove'... // Event Listener with trigger when mouse is moved over the element
...'transitionend'... // Event Listener with trigger when the transistion ends
document.getElementById("green").onclick = funcGreen // Old Method / Waiting for click on this element (by ID) as a "event-listener"
""
=> E.G. document.querySelector('=>idBlue').addEventListener('click',changeToBlue)
""
function funcGreen() { // Define function
document.querySelector("body")
.style.backgroundColor = "rgba(241,63,247,1)" // Change BackGroundColor-Style to rgba-color green (as inlinecode in the rendering - not in the html-code)
document.querySelector("body").style.color = "white" // Change Fontcolor to white (as inlinecode in the rendering - not in the html-code)
}
""
=> Use EventListner for alle elements with a specific class
""
let elements = document.querySelectorAll(".panel"); // Select all elements with class "panel"
elements.forEach(elem => elem.addEventListener("click",func1)) // Iterate trough every element and create EventListener - when clicked start func1 for the element
function func1() { // Function is run with the activated Element for the EventListener
this.classlist.toggle("newClass")}
""
document.getElementById => Old Method / Select an element by ID
document.querySelector("xyz") => New Method / Select (first) a <tag> or .class or =>id
const c = document.querySelectorAll("h2") => Select all elements which have h2 and store it in the constante c
.onclick => Element-Listener waiting for a click7
.style.backgroundColor => Change BackgroundColor
.style.color => Change Font Color
.style.display = "none" => Hide element in DOM
.innerText = "xyz" => Change Text of the selected element
.innerText = v1 + " " + v2 + " " + v3 => Concatenate 3 variables with space between (old method)
.innerText = `${v1} ${v2} ${v3}` => Concatenate 3 variables with space between (new method with the "`"-char called template string)
.value => Read the value/text of the field
.id => Show the ID of the selected element
.src => Set the src of a image
.className = "MyClass"; => Change class of the element to "MyClass"
.classList => Manipulate classes informations
.classList.toggle("hidden") => Toggle the class hidden (when triggered class is deleted OR added (when the next click occured)
.classList.add("hidden") => Add the class hidden
.classList.contains("cl") => Check if element contains class "cl"
.classList.remove("wiggle") => Remove the class from the element
setInterval(func1, 1000) => Call function "func1" every second (1000ms)
setInterval(()=> {do something},10000) => Do something any 10 seconds
setTimeout(func1, 2000) => Func1 is running with a delay of at least 2 seconds (with own seperate function)
setTimeout(()=> {do something},1000) => Do something and wait 1 second (function direct in the statement)
=> Add some elments to an ul-element
""
var li = document.createElement("li") // create new li-element
li.textContent = "new text" // add text to the new element
document.querySelector("ul").appendChild(li) // append the new li-element to the ul-element
""
###### CSS VARIABLE HANDLING
=> Read all control- and input-elements<br>
Output is not an array - its a node-list (does not have all methods like an array)
""
let inputs = document.querySelectorAll(".controls input");
""
inputs.forEach(input => input.addEventListener("change", handleUpdate)); => Wait for change in any element and call the function "handleUpdate"
=> Handle Update<br>
(For definition and using the variables in CSS have a look at CSS.txt)
""
function handleUpdate() {
const suffix = this.dataset.sizing || ''; // read the sizing-parameter for the triggered element (used data-sizing in html)
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
// set the variable in css (name according to --name in css)
// use the value from the read element from the adventlistener
// and use the suffix which is read above
// full property looks eg. like "--spacing: 10px"
}
""
###### API ACCESS
<a href="https://learn.shayhowe.com/advanced-html-css/jquery/" style="font-style: italic">https://learn.shayhowe.com/advanced-html-css/jquery/</a>
=> request data from API get data back in JSON format
=> Reading / Fetching the informations from an API-url
=> Request the API-content and output as JSON-information
=> alle the information is stored in data
=> last part is the error handling when something wrong happens
""
fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(err => {
console.log("error ${err}")
});
""
=> Using a API using async / await
""
async function getSomethingFromAPI() {
const res = await fetch("url").catch(e => {
console.log("Error - Fetch not possible...")
})
if (!data) {
console.log("Error - Data / JSON wrong...")
} else {
const data = await res.json()
console.log(data)
}
}
getSomethingFromAPI()
""
=> sometimes the URL also has a search query parameter<br>
eg. <a href="https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita" style="font-style: italic">https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita</a><br>
"s" is the parameter and "margarita" the serach string<br>
eg. <a href="https:/api.nasa.gov/planetary/apod?api_key=DemoKey&date=2020-10-10" style="font-style: italic">https:/api.nasa.gov/planetary/apod?api_key=DemoKey&date=2020-10-10</a><br>
here are used 2 parameters - one "api-key" and the second "data"
=>eg. use horoscope api<br>
<a href="https://aztro.readthedocs.io/en/latest/" style="font-style: italic">https://aztro.readthedocs.io/en/latest/</a><br>
need to use browserify<br>
<a href="http://browserify.org/#install" style="font-style: italic">http://browserify.org/#install</a><br>
so the require can also run with html (otherwise it only works in the IDE)<br>
parse the JSON-content to an object: let obj = JSON.parse(body)
###### JQUERY
=> library for javascript<br>
- Traversing<br>
- Manipulating<br>
- Events<br>
- Effects
<script src="=>ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> => include before body-tag
$(document).ready(function(event){...}); => put all jQuery code in this function (waiting until the the page has loaded an the DOM is ready)
$('.feature'); => Class selector
$('li strong'); => Descendant selector
$('em, i'); => Multiple selector
$('a[target="_blank"]'); => Attribute selector
$('p:nth-child(2)'); => Pseudo-class selector
###### DATE
let now = new Date() => Assign variable to actual date
let t1 = Date.now() => Returns numeric acttual date as number (helpful to calculate some timespans)
let secondes = now.get.Seconds() => Assign actual seconds from actual date variable "now"
calcDate.toISOString().split('T')[0] => Convert datetime-object to string in format "yyyy-mm-dd"
###### MATH
Math.floor(Math.random()*6) + 1 => Random number between 1 and 6 like a cube (Math.random returns value between 0 and 1)
Math.ceil(43.8) => Nearest Upward rounding => 44
Math.sqrt(9) => Return the square-root => 3
Math.PI => Use PI
Math.floor(5.95) => Round down the float => 5
Math.pow(2,3) => First number to the power of the second => 8
Math.cbrt(8) => Creates the cube root => 3
Math.abs(-3) => Returns the absolute number => 3
Math.min(1,2,3) => Returns the Minimum of the values => 1
Math.max(1,2,3) => Returns the Maximum of the values => 3
###### LOCAL STORAGE
=> Allows to store data across browser sessions
localStorage.setItem ("name","Bob") => Set item to local storage (name is the key and Bob is the value)
localStorage.getItem ("name") => Get item from local storage (name is the key)
localStorage.delItem ("name") => Delete item from local storage (name is the key)
localStorage.clear() => Delete the whole local storage
###### MODULE EXPORTS
=> Define module with Node.js (in a file)
""
let Obj = {} // define an object
Obj.prop = "xyz" / define something in the object eg. a function
module.exports = Obj // export the file as module to node.js
""
=> Use a module
""
const Obj = require('./module.js'); // import the module for using
Obj.funcFromModule // use the function from the module
""
=> Define module with export
""
let Menu = {};
export default Menu;
""
=> Import module with import
""
import Menu from './menu';
""
###### ASYNCHRONOUS HANDLING
=> running synchronous - outputs 1,2,3
""
function houseOne(){ console.log('Paper delivered to house 1')}
function houseTwo(){console.log('Paper delivered to house 2')}
function houseThree(){console.log('Paper delivered to house 3')}
houseOne()
houseTwo()
houseThree()
""
=> running asynchronous - outputs 1,3 and then after 3 seconds 2
=> in the 2nd function the setTimeout-api is called with a delay of 3000ms / 3 seconds
""
function houseOne(){ console.log('Paper delivered to house 1')}
function houseTwo(){
setTimeout(() => console.log('Paper delivered to house 2'), 3000)
}
function houseThree(){console.log('Paper delivered to house 3')}
houseOne()
houseTwo()
houseThree()
""
=> running asynchronous - outputs 1, after 3sec => 2 and immediately afterwards 3
=> the 2nd function is using a callback (using a function)
=> setTimeout is called with a 3sec delay - then 2 is printed - and then with callback() 3 as the argument of the function 2
""
function houseOne(){ console.log('Paper delivered to house 1')}
function houseTwo(callback){
setTimeout(() => {
console.log('Paper delivered to house 2')
callback()
}, 3000)
}
function houseThree(){console.log('Paper delivered to house 3')}
houseOne()
houseTwo(houseThree)
""
=> using a promise (promise is an object)
""
const promise = new Promise((resolve, reject) => { // define the promise and asign to a variable
const error = false
if(!error){
resolve('Promise has been fullfilled') // when the promise is resolved
}else{
reject('Error: Operation has failed') // when there is an error
}
})
console.log(promise)
promise
.then(data => console.log(data)) // doing this when the promise is resolved
.catch(err => console.log(err)) // doing this when the promise is not resolved has an error
""
=> using async / await
""
function houseOne(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Paper delivered to house 1')
}, 1000)
})
}
function houseTwo(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Paper delivered to house 2')
}, 5000)
})
}
function houseThree(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Paper delivered to house 3')
}, 2000)
})
}
async function getPaid(){ // defining a async function
const houseOneWait = await houseOne() // awaits the ending of function houseOne
const houseTwoWait = await houseTwo() // waiting for ending function houseTwo
const houseThreeWait = await houseThree() // waiting for ending function houseThree
console.log(houseOneWait)
console.log(houseTwoWait)
console.log(houseThreeWait)
}
getPaid() // after 5seconds (longest functtion running) the output is done
""
=> create an executor function
""
const executorFunction = (resolve, reject) => {
if (someCondition) {
resolve('I resolved!');
} else {
reject('I rejected!');
}
}
""
const myFirstPromise = new Promise(executorFunction) => construct a new variable with "new Promise"
=> example for a promise handling with resolve, reject and .then
""
let prom = new Promise((resolve, reject) => {
let num = Math.random();
if (num < .5 ){
resolve('Yay!');
} else {
reject('Ohhh noooo!');
}
});
const handleSuccess = (resolvedValue) => {
console.log(resolvedValue);
};
const handleFailure = (rejectionReason) => {
console.log(rejectionReason);
};
prom.then(handleSuccess, handleFailure);
""
=> example using a promise with .then and .catch
=> .then is handling the resolved part and .catch is handling the rejected part
""
prom
.then((resolvedValue) => {
console.log(resolvedValue);
})
.catch((rejectionReason) => {
console.log(rejectionReason);
});
""
=> define a async-function with function declaration:
""
async function myFunc() {
// Function body here
};
""
=> define a async-function with function expression
""
const myFunc = async () => {
// Function body here
};
""
=> example for handling a async function
""
async function withAsync(num){
if (num === 0){
return 'zero';
} else {
return 'not zero';
}
}
""
###### REQUESTS
const xhr = new XMLHttpRequest() => create xml http request object instances
const url = 'https://api-to-call.com/endpoint' => assing the url
xhr.responseType = 'json' => set the resonse type to json
xhr.onreadystatechange = () => {} =>
=> use GET statement for reading an URL
""
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
xhr.open('GET', url);
xhr.send();
};
""
=> use POST statement for writing something back to an URL
""
const xhr = new XMLHttpRequest();
const url = 'https://api-to-call.com/endpoint';
const data = JSON.stringify({id: '200'});
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
return xhr.response;
}
}
xhr.open('POST', url);
xhr.send(data);
""
###### NODE.JS
home of node.js => https://nodejs.org/en/
docu of the modules => https://nodejs.org/dist/latest-v15.x/docs/api/
node --version => check if and which node.js version is installed
npm --version => node package manager - show the installed version
npm init => create a package.json files with all necessary project informations
npm init -yarn => initialize node-project - with the parameter "-y" without prompting for additonal informations
npm install uuid => install module "uuid" - node_modules folder is created - dependencie is added to package.json
npm install -D nodemon => install module as development dependencie
npm install => install all modules according to the dependencies in the package.json
npm update => update the dependencies of the project
npm i ejs dotenv => install several modueles in one line
=> how to link 2 js-files
""
// in the first file:
const pers = { // define object in a file
name: "John",
age: 30
}
module.exports = pers // make object usable for other files