-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript.csv
We can make this file beautiful and searchable if this error is corrected: Any value after quoted field isn't allowed in line 3.
984 lines (954 loc) · 54.5 KB
/
javascript.csv
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
Comments in Javascript;// Comment something;javascript
Multiline comments;/*Text xzy*/;javascript
"Declare and assign string (possible with """" or '') - ""var"" was the earlier version in the past for that";"let intStr = ""7""";javascript
Linebreak and Tab should not used - is morely css-stuff for formating;"""/n /t""";javascript
Declare a variable and assign int (also signed int like -36);let age = 24;javascript
Defining without assigning (var gets value undefined);let var;javascript
Define 2 variables (one without value and one with value);let var, age = 25;javascript
Define and assign 3 variables (a=5, b=8, c=12);let [a, b, c] = [5, 8, 12];javascript
Declare a constant and assign int (constant can not be changed like variables);const age = 25;javascript
Declare and assign float (also signed float like +4.5763;let float = 5.14876;javascript
Change String to Int with base 10;"let intNum = parseInt(intStr,10);";javascript
Declare and assign string;"let floatStr = ""5.14673""";javascript
Change String to Float;"let floatNum = parseFloat(floatStr);";javascript
"Defines+Assigns a variable (if user exists/has a value use that - otherwise initialize with ""guest""";"let v = user || ""guest""";javascript
Open windows for entering something and store in const inp;"const inp = prompt(""Enter:"")";javascript
Convert numeric value to string;num.toString();javascript
2nd method to convert numeric value to string;"num + """"";javascript
3rd method to convert number / int to a String;String(n);javascript
Converts String to Number / Int;Number(s);javascript
"Shows the type of the variable as string (eg. ""number"", ""string"", ""boolean"")";typeof (x);javascript
Modulo / Rest of the division (=> 1);7 % 2;javascript
Check 2 values / variables (result in true / false);x == y;javascript
Equal value and equal type;x === y;javascript
Not equal;x != y;javascript
Not equal value and not equal type;x !== y;javascript
Greater, lesser, greater + equal , lesser + equal;>,<,>=,<=;javascript
Check if value is NaN (NotANumber) - eg. when converting with Number() and the value is no number;isNaN(x);javascript
Check if n is a integer;Number.isInteger(n);javascript
Makes variable +1;"num++;";javascript
Outputs variable num in console;console.log(num);javascript
Outputs element as table (eg. for objects, arrays);console.table(object);javascript
Alert information in a window;"alert(""Text!"")";javascript
"Alert some text with outputing the variable ""name"" between (using backticks ""`""";alert(`Bla ${name} bla`);javascript
Round to 2 decimal digits;n = n.toFixed(2);javascript
Swap 2 variables;[x, y] = [y, x];javascript
Exit javascript node program;process.exit(1);javascript
Define a string;"let s = ""this is a test""";javascript
String with linebreak \n;"let s = ""this \n text""";javascript
extract only the first character;s.slice(0,1);javascript
last char of a string;s.slice(-1);javascript
slicing 2 chars from pos 3 and 4;s.slice[3,5];javascript
slice from pos 3 to the end;s.slice[3];javascript
shows the length of the string;s.length;javascript
Lowercase the whole string;s = s.toLowerCase();javascript
Uppercase the whole string;s = s.toUpperCase();javascript
Returns the second char of a string;s.charAt(1);javascript
"Search if ""xyz"" is int the string - returns the position where found - when not found returns -1";"s.search(""xyz"")";javascript
Check if string/chars are in;"s.includes(""ee"")";javascript
"Replace ""abc"" with ""xyz"" for any occurrences in the string (only working for new browsers!)";"sNew = s.replaceAll(""abc"",""xyy)";javascript
2nd method for replacing everything (works for more browsers!);"sNew = s.replace(/abc/g,""xyz"")";javascript
Concatenate 2 strings;sNew = s1.concat(s2);javascript
Delete all whitespaces at the beginning and the end;s.trim();javascript
Repeat string 3 times;s.repeat(3);javascript
Split the words in a array;"s.split("" "")";javascript
Delete all whitespaces at the beginning and the end;s.trim();javascript
Fills leading zero in a string with allways 3 chars - eg. 006;"s.padstart(3,""0"")";javascript
Find Index of first occurence of this string;"s.indexOf(""ee"")";javascript
Outputs the x character in the string => second char of the string (same as s[1]);s.charAt(1);javascript
Get the last 3 chars of the string;s.slice(-3);javascript
2nd variant: Get the last 3 chars of the string;s.substr(s.length-3);javascript
Return Ascii-Code of the first character of the string;s.charCodeAt(0);javascript
"Returns True if the string end with ""?""";"s.endsWith(""?"")";javascript
Returns char for specific ascii-code;char = String.fromCharCode(65);javascript
Check if char is in A-Z;char.match(/[A-Z]i);javascript
Spread-Operator for string (=> build array with each character);[...s];javascript
Convert object-element to string;s = JSON.stringify(obj);javascript
"Convert datetime-object to string in format ""yyyy-mm-dd""";calcDate.toISOString().split('T')[0];javascript
Define an array;"let arr = [];";javascript
Define an array and initialize it;"let arr = [6,7,8];";javascript
Define multidim array;let mat= [[1,2,3],[4,5,6],[7,8,9]];javascript
Get second element => 7;arr[1];javascript
Access last element in array;arr[arr.length-1];javascript
Get element in the matrix => 5;mat[1][1];javascript
Replace the third element;arr[2] = 9;javascript
"Returns list as a string => ""6,7,8""";String(Arr);javascript
Must allways be compared with triple = (only == would be wrong);a1 === a2;javascript
Total count of the elemets in the array;arr.length;javascript
Extracts and delete element at the end (fast!);arr.pop();javascript
Extracts and delete element at the begin (slow!);arr.shift();javascript
Append new elements to the array at the end (fast!);"arr.push(""X"",""Y"")";javascript
Add new elements to the array at the beginning (slow!);"arr.unshift(""Y"",""Z"")";javascript
Copy elements from index 2 to index 3 => result is one char at index 2;ergArr = arr.slice(2,3);javascript
Copy the last 2 elements of the array;ergArr = arr.slice(-2);javascript
Delete 1 element beginning from index 2;arr.splice(2,1);javascript
Delete 2 elements beginning from the index 0 - and insert the elements 10 and 11;arr.splice(0,2,10,11);javascript
From index -1 delete 0 elements and add 3 and 4;arr.splice(-1,0,3,4);javascript
Delete 2 elements beginning from the index 0 - and assign them to ergArr;ergArr = arr.splice(0,2);javascript
x > 0) => Return true if all elements are bigger than 0;arr.every(x;javascript
Concatenate 2 arrays to one;ergArr = arr1.concat(arr2);javascript
"Returns first index position of element ""xyz"" (if not exists result is -1)";"arr.indexOf(""xyz"")";javascript
"Return the last index position of the element ""xyz""";"arr.lastIndexOf(""xyz"")";javascript
Check if string exists in the array;"arr.includes(""xyz"")";javascript
Reverse the entire array;arr.reverse();javascript
Split the words in a array;"arr = varStr.split("" "")";javascript
"Join the elements from the array in a string with "", "" as seperator";"varStr = arr.join("", "")";javascript
Check if object is an array (if array = true);Array.isArray(arr);javascript
Iterate through index of the array;"for (let i=0; i < arr.lenth; i++) {do smth.}";javascript
Iterate through array elements;for (let elem of arr) {alert(arr)};javascript
Convert a node-list to an array;"arr=Array.from(document.querySelectorAll(""a""))";javascript
2nd method for converting node-list to an array;"arr=[...document.querySelectorAll(""a"")]";javascript
"Concatenate the array to a string seperated by "" """;"arr.join("" "")";javascript
a > b ? 1 : -1) => Order array ascending;arr.sort((a,b);javascript
a > b ? -1 : 1) => Order array descending;arr.sort((a,b);javascript
Ordering long method with function;arr.sort(function(a,b) {return a > b ? 1 : -1};javascript
Find max value in an array with spread operator;Math.max(...arr);javascript
Find min value in an array with spread operator;Math.min(...arr);javascript
"Array Destrucuring Expl1 (a will be ""Ha"" and b will be ""Ho""";"let [a,b] = [""Ha"",""Ho"",""Hi"",""He""]";javascript
"Array Destrucuring Expl2 (a will be ""Ha"" and d will be ""He""";"let [a,,,d] = [""Ha"",""Ho"",""Hi"",""He""]";javascript
"Array Destrucuring Expl3 (a will be ""Ha"" and rest will be [""Ho"",""Hi"",""He""]";"let [a,...rest] = [""Ha"",""Ho"",""Hi"",""He""]";javascript
Swapping values (a will be b and b will be a);[a,b] = [b,a];javascript
(return is not working here - forEach loops are allways running for all elements);"arr.forEach((elem,idx) => {
console.log(idx)
console.log(elem)
})";javascript
(return is not working here - forEach loops are allways running for all elements);"arr.forEach(function(elem,idx) {
console.log(idx)
console.log(elem)
})";javascript
Iterate trough an array with 1sec pause at every element;"names.forEach((name, i) => {
setTimeout(() => {
display(name);
}, i * 1000);
});";javascript
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);";javascript
Map Method - Long Method (for more code);"let newarr = arr.map (function(x) {
x = x * 2
}";javascript
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
}
})";javascript
Filter Method - Short Method in one line;"let newarr = arr.filter(x => x > 6);";javascript
"every element is added to total - 0 is the default value of ""total""";"erg = arr.reduce ((total, elem) => {
return total + elem
},0)";javascript
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;
})";javascript
1st line defines the check function - 2nd line checks the array with the function;"const even = (element) => element % 2 === 0;
arr.some(even)";javascript
1st line defines the check function - 2nd line checks the array with the function;"const isLower = (elem) => elem < 40;
arr.every(isLower)";javascript
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!');";javascript
the first and second message will appear immediately - the middle message only after 2 seconds;"if (condition is true) {
=>Do something
}else if (condition is true){
=>Do something else
}else{
=>Default else
}";javascript
If structure with logical and;"if (a == 9) && (b == 7) { c = ""Hurra!"" }";javascript
If structure with logical or;"if (a == 9) || (b == 7) { c = ""Hurra!"" }";javascript
If structure with logical not;if !(a > 13);javascript
if !(a > 13) If structure with logical not;"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;
}";javascript
Iteration from 1 to 5 with for-loop;"for (let i=1; i<=5; i++) {}";javascript
Iteration backwards from 3 to 0 with for-loop;"for (let i=3; i>=0; i--) {}";javascript
Iterate through an array;"for (let i=0; i<arr.length; i++) {}";javascript
Iterate through a string;for (let char of text) {};javascript
Iterate through the keys of an object;for (let key in obj) {};javascript
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);
}";javascript
While loop with break condition;"while (x < 4) {
if xyz === ""abc"" {break}
}";javascript
Do While loop with break condition;do {} while (x < 4);javascript
Endless while loop - has to be exited somewhere;while (true) {};javascript
Iterate through array by elements (x);"arr.forEach((x) => {
console.log(x)
})";javascript
Are all falsy values - can checked with if (xyz)...;"0,"""",'',null,undefined,NaN";javascript
Ternary Operator for if - if isNight=true then s=Night - else s=Day;"isNight ? s=""Night"" : s=""Day""";javascript
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";javascript
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";javascript
Anonymous Function with Fat Arrow syntax;"const add = (x,y) => {...}
add(3,5) // Function Call
let h = a => a % 3 // Even shorter without parentees";javascript
"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 ""||""";javascript
Use Rest Parameters to accept any number of arguments;"function max(...numbers) { // Any numbers of arguments
=> do something with a loop
}";javascript
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);";javascript
Define an object (literal syntax);let obj = {};javascript
2nd method to define object (construtor syntax);let obj = new Object();javascript
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!""
}
}";javascript
"Access property / shows value of the key ""name"" (1st method) => John (dot.notation)";obj.name;javascript
"Shows value of the key ""name"" (2nd method) => John (bracket notation)";"obj[""name""]";javascript
"Shows key ""age"" of the object => 30 (dot notation)";obj.age;javascript
Add a new propertie to the object;"obj.newOne = ""xyz""";javascript
Add a new method to the object;obj.newMethod = function(var) {...do someth...};javascript
Call the new method;obj.newMethod(25);javascript
Check if key is in the object;age in obj;javascript
Delete a property of an object (dot notation);delete obj.age;javascript
Delete a property of an object (bracket notation);"delete obj[""age nr""]";javascript
Check if a property / method is in an object;"if (""property"" in obj) {...}";javascript
Read the keys of an object into an array;arr = Object.keys(obj);javascript
Read the values of an object into an array;arr = Object.values(obj);javascript
Read alle key / value pairs of an object into an (nested) array;arr = Object.entries(obj);javascript
Check if xyz i part of the object;"obj.hasOwnProperty(""xyz"")";javascript
Check if Object is empty;Object.keys(obj).length === 0 && obj.constructor === Object;javascript
Iterate through the keys of the object and outputs key and value;"for (let key in obj) {
console.log(key, obj[key]
}";javascript
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']
};";javascript
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";javascript
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"")
}
}
}";javascript
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";javascript
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!""
}";javascript
"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;
}";javascript
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;
}
}";javascript
Define static function - this can only be done for the class itself (or for the instances of the class);static generateName() {...};javascript
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""";javascript
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)
}";javascript
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"")}";javascript
Old Method / Select an element by ID;document.getElementById;javascript
New Method / Select (first) a <tag> or .class or =>id;"document.querySelector(""xyz"")";javascript
Select all elements which have h2 and store it in the constante c;"const c = document.querySelectorAll(""h2"")";javascript
Element-Listener waiting for a click7;.onclick;javascript
Change BackgroundColor;.style.backgroundColor;javascript
Change Font Color;.style.color;javascript
Hide element in DOM;".style.display = ""none""";javascript
Change Text of the selected element;".innerText = ""xyz""";javascript
Concatenate 3 variables with space between (old method);".innerText = v1 + "" "" + v2 + "" "" + v3";javascript
"Concatenate 3 variables with space between (new method with the ""`""-char called template string)";.innerText = `${v1} ${v2} ${v3}`;javascript
Read the value/text of the field;.value;javascript
Show the ID of the selected element;.id;javascript
Set the src of a image;.src;javascript
"Change class of the element to ""MyClass""";".className = ""MyClass"";";javascript
Manipulate classes informations;.classList;javascript
Toggle the class hidden (when triggered class is deleted OR added (when the next click occured);".classList.toggle(""hidden"")";javascript
Add the class hidden;".classList.add(""hidden"")";javascript
"Check if element contains class ""cl""";".classList.contains(""cl"")";javascript
Remove the class from the element;".classList.remove(""wiggle"")";javascript
"Call function ""func1"" every second (1000ms)";setInterval(func1, 1000);javascript
{do something},10000) => Do something any 10 seconds;setInterval(();javascript
Func1 is running with a delay of at least 2 seconds (with own seperate function);setTimeout(func1, 2000);javascript
{do something},1000) => Do something and wait 1 second (function direct in the statement);setTimeout(();javascript
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";javascript
Read all control- and input-elements;"let inputs = document.querySelectorAll("".controls input"");";javascript
"input.addEventListener(""change"", handleUpdate)); => Wait for change in any element and call the function ""handleUpdate""";inputs.forEach(input;javascript
Handle Update;"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""
}";javascript
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}"")
});";javascript
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()";javascript
"ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js""></script> => include before body-tag";"<script src=""";javascript
put all jQuery code in this function (waiting until the the page has loaded an the DOM is ready);"$(document).ready(function(event){...});";javascript
Class selector;"$('.feature');";javascript
Descendant selector;"$('li strong');";javascript
Multiple selector;"$('em, i');";javascript
Attribute selector;"$('a[target=""_blank""]');";javascript
Pseudo-class selector;"$('p:nth-child(2)');";javascript
Assign variable to actual date;let now = new Date();javascript
Returns numeric acttual date as number (helpful to calculate some timespans);let t1 = Date.now();javascript
"Assign actual seconds from actual date variable ""now""";let secondes = now.get.Seconds();javascript
"Convert datetime-object to string in format ""yyyy-mm-dd""";calcDate.toISOString().split('T')[0];javascript
Random number between 1 and 6 like a cube (Math.random returns value between 0 and 1);Math.floor(Math.random()*6) + 1;javascript
Nearest Upward rounding => 44;Math.ceil(43.8);javascript
Return the square-root => 3;Math.sqrt(9);javascript
Use PI;Math.PI;javascript
Round down the float => 5;Math.floor(5.95);javascript
First number to the power of the second => 8;Math.pow(2,3);javascript
Creates the cube root => 3;Math.cbrt(8);javascript
Returns the absolute number => 3;Math.abs(-3);javascript
Returns the Minimum of the values => 1;Math.min(1,2,3);javascript
Returns the Maximum of the values => 3;Math.max(1,2,3);javascript
Set item to local storage (name is the key and Bob is the value);"localStorage.setItem (""name"",""Bob"")";javascript
Get item from local storage (name is the key);"localStorage.getItem (""name"")";javascript
Delete item from local storage (name is the key);"localStorage.delItem (""name"")";javascript
Delete the whole local storage;localStorage.clear();javascript
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";javascript
Use a module;"const Obj = require('./module.js'); // import the module for using
Obj.funcFromModule // use the function from the module";javascript
Define module with export;"let Menu = {};
export default Menu;";javascript
Import module with import;"import Menu from './menu';";javascript
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()";javascript
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()";javascript
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)";javascript
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";javascript
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";javascript
create an executor function;"const executorFunction = (resolve, reject) => {
if (someCondition) {
resolve('I resolved!');
} else {
reject('I rejected!');
}
}";javascript
"construct a new variable with ""new Promise""";const myFirstPromise = new Promise(executorFunction);javascript
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);";javascript
.then is handling the resolved part and .catch is handling the rejected part;"prom
.then((resolvedValue) => {
console.log(resolvedValue);
})
.catch((rejectionReason) => {
console.log(rejectionReason);
});";javascript
define a async-function with function declaration:;"async function myFunc() {
// Function body here
};";javascript
define a async-function with function expression;"const myFunc = async () => {
// Function body here
};";javascript
example for handling a async function;"async function withAsync(num){
if (num === 0){
return 'zero';
} else {
return 'not zero';
}
}";javascript
create xml http request object instances;const xhr = new XMLHttpRequest();javascript
assing the url;const url = 'https://api-to-call.com/endpoint';javascript
set the resonse type to json;xhr.responseType = 'json';javascript
{} =>;xhr.onreadystatechange = ();javascript
use GET statement for reading an URL;"xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
xhr.open('GET', url);
xhr.send();
};";javascript
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);";javascript
https://nodejs.org/en/;home of node.js;javascript
https://nodejs.org/dist/latest-v15.x/docs/api/;docu of the modules;javascript
check if and which node.js version is installed;node --version;javascript
node package manager - show the installed version;npm --version;javascript
create a package.json files with all necessary project informations;npm init;javascript
"initialize node-project - with the parameter ""-y"" without prompting for additonal informations";npm init -yarn;javascript
"install module ""uuid"" - node_modules folder is created - dependencie is added to package.json";npm install uuid;javascript
install module as development dependencie;npm install -D nodemon;javascript
install all modules according to the dependencies in the package.json;npm install;javascript
update the dependencies of the project;npm update;javascript
install several modueles in one line;npm i ejs dotenv;javascript
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
// in the second file:
const person = require(""./person"") // use person from other file
console.log(person)";javascript
Setup a simple server;"const http = require(""http"")
const fs = require(""fs"")
http.creatorServer((req,res) => {
fs.readFile(""demofile.html"", (err, data) => {
res.writeHead(200, {""Content-Type"": ""text/html""})
res.write(data)
res.end()
})
}).listen(8000)";javascript
The path module provides utilities for working with file and directory paths.;"const path = require(""path"") // include module
console.log(__filename) // outputs the whole path of the file
path.basename(__filename) // outputs only the filename
path.dirname(__filename) // outputs the dirname of the file
path.extname(__filename) // outputs the extention of the file
path.parse(__filename) // outputs several infos as object (root,dir,base,ext,name)
path.parse(__filename).base // outputs only the base filename
path.join(__dirname, ""test"", ""hello.html"") // use dirname and appends the 2 text-infos to the path";javascript
The fs module enables interacting with the file system;"// Create folder
fs.mkdir(path.join(__dirname, ""/test""), {}, (err) => {
if (err) throw err;
console.log(""Folder created..."")
})
// Create and (over)write to file
// write file to the joined path
// name of the file is ""hello.txt""
// content of the file is ""Hello World!""
fs.writeFile(path.join(__dirname, ""/test"", ""hello.txt""), ""Hello World!"", (err) => {
if (err) throw err
console.log(""File written to..."")
})
// Create and append to file
fs.writeFile(path.join(__dirname, ""/test"", ""hello.txt""), ""Hello World!"", (err) => {...})
// Read file
fs.readFile(path.join(__dirname, ""/test"", ""hello.txt""), ""utf8"", (err, data) => {
if (err) throw err
console.log(data)
})
// Rename file
fs.rename(path.join(__dirname, ""/test"", ""hello.txt""),
path.join(__dirname, ""/test"", ""hello2.txt""), (err, data) => {
if (err) throw err
console.log(""File renamed..."")
})";javascript
include module;"const path = require(""os"")";javascript
outputs the os platform (eg. win32 for windows, darwin for macos);os.platform();javascript
outputs architecture (eg. x64, x32);os.arch();javascript
cpu informations (model,speed,times for every core);os.cpus();javascript
free memory (eg. 18717655040);os.freemem();javascript
total memory (eg. 34237403136 for 32GB RAM);os.totalmem();javascript
home directory of the user (eg. c:\Users\Max);os.homedir();javascript
uptime of the computer in seconds (eg. 13463);os.uptime();javascript
os.uptime() uptime of the computer in seconds (eg. 13463);"=> Module url
=> The url module provides utilities for URL resolution and parsing.
const url = require(""url"") => include module
const myUrl = new URL(""https://www.xyz.com"") => assign URL
myUrl.href => the whole url (eg. https://www.rapidtech1898.com/htmlFinanztools/en/aktienbewertungInSekundenEN.html)
myUrl.toString() => 2nd method to get the whole url
myUrl.hostname => the hostname of the url (eg. www.rapidtech1898.com)
myUrl.host => the host of the url (including port number - when it exists in the url)
myUrl.pathname => the pathname (eg. /htmlFinanztools/en/aktienbewertungInSekundenEN.html)
myUrl.search => the search-parameters of the url (eg. ?id=100&status=active)
myUrl.searchParams => show parameters (eg. URLSearchParams { 'id' => '100', 'status' => 'active' }
myUrl.searchParams.append('abc','123') => add a parameter with id=abc and value=123
=> Loop through params";javascript
console.log(`${name}: ${value}`));myUrl.serachParams.forEach((value,name);javascript
myUrl.serachParams.forEach((value,name) console.log(`${name}: ${value}`));"=> Module http
=> The HTTP interfaces in Node.js are designed to support many features of the protocol
const http = require(""http"") => include module";javascript
{;http.createServer((req, res);javascript
"console.log(""Server running..."")) // running on port 5000";}).listen(5000, ();javascript
"}).listen(5000, () console.log(""Server running..."")) // running on port 5000";=> Simple Server;javascript
{;http.createServer((req, res);javascript
{ // reads file and shows it in browser;fs.readFile('demofile.html', (err, data);javascript
fs.readFile('demofile.html', (err, data) { // reads file and shows it in browser;=> Simple GET-API;javascript
{;"app.get(""/"", (request, response)";javascript
{ // server listening on port 8000;app.listen(PORT, ();javascript
app.listen(PORT, () { // server listening on port 8000;=> Server with Client connection;javascript
{ // returns the savage object;"app.get(""/api/savage"", (request, response)";javascript
{ // listen on port (first entry for hosting on eg. horuku - second one for localhost);app.listen(process.env.PORT || PORT, ();javascript
"JSX: show the ""title"" only when ""showtitle"" is true using a ternary expression";"{showTitle ? title : """"}";javascript
"Define States with default value """" (title is the state, setTitle the state-function)";"const [title, setTitle] = useState("""")";javascript
app.listen(PORT, () { // server listening on port 8000;"###### REACT
=> Javascript library for building user interfaces especially for single-page applications (like facebook, twitter etc.)
=> React allows developers to create large web applications that can change data, without reloading the page
components => webpage is divided in many components (like on facebook)
props => every component has some properties (size, color, shape, etc.) - arguments are passed into components
states => and components have states (like the counter for likes / dislikes / unread messages etc.) - if state changed => component has to react and re-render
react => contains the APIs for creating components
react-dom => contains the APIs for rendering to the browser DOM
JSX => syntax extension to JS
npx create-react-app nameProject => create react app in a folder with the name ""nameProject""
npm install --global yarn => install yarn (if not allready installed)
yarn start => start the react app (default on http://localhost:3000/)
standard-folder ""public"" / index.html => is the base setup for html-file (important is <div id=""root""></div> - where everything get rendered from react)
standard-folder ""public"" / favicon.ico => icon of the tab
standard-folder ""public"" / manifest.json => name, shortname of the react-app (description of the application)
standard-folder ""src"" / index.js => entry-point for the react-app (get everything from App and render this to the div-element with the root-id)
standard-folder ""src"" / app.js => main react-app called App
<Info></Info> => call the component ""Info""
<Info /> => 2nd method to call the component ""Info""
{title} => JSX: use the variable ""title"" in the react html code
<AddItem text=""blabla"" number={2} /> => Define a prop ""text"" in a component-call and a numeric prop ""number""
function AddItem(props) => Use the props in the component (access with props.text or props.number)
function AddItem(text, number) => Or use the props destructured in the component
function AddItem({text, number=99}) => Define component with default prop for ""number""
<p>{props.number}</p> => Render the props.number in a paragraph-tag
import { useState } from ""react"" => Import useState
const [count, setCount] = useState(0) => Define States with default value 0 (count is the state, setcount the state-function)
<p>Title: {title} </p> => Use the variable in the tags
<button onClick={updateCounterClicked}>Update Counter</button> => function is called when the button is pressed
const updateCounterClicked = () => {setCount(count + 1)} => count i incread by one in the function (=when the button is pressed)
=> Use component in a seperate file";javascript
app.listen(PORT, () { // server listening on port 8000;=> Simplest possible App.js file;javascript
app.listen(PORT, () { // server listening on port 8000;=> Example for a component with class based syntax;javascript
app.listen(PORT, () { // server listening on port 8000;"<p>Manage your stuff</p>
</div>
)
}
}
export default Info;";javascript
Example (with old Class syntax);"index.html in folder <public> with: <div id=""root""></div>
=> defines initial root-element where all the input goes to
index.js in folder <src> with: ReactDOM.render(<App />, document.getElementById('root'));
=> renders APP and put this in the div with id=root
app.js
=> Import components with:
import React, { Component } from 'react';
import './App.css';
import Header from './Header';
import SectionMain from './SectionMain';
import Aside from './Aside';
import Footer from './Footer';
=> Render components
class App extends Component {
render() {
return (
<div className=""App"">
// call Header with the 2 props
<Header backColor=""green"" width=""50%""></Header>
<SectionMain></SectionMain>
<Aside></Aside>
<Footer></Footer>
</div>
);
}
}
footer.js
=> Import react and styling-file
import React, { Component } from 'react';
import './Footer.css';
=> Render components
class Footer extends Component {
render() {
return (
<footer className=""Footer"">
</footer>
);
}
}
export default Footer;";javascript
NODE.JS;"Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that
runs on the V8 engine and executes JavaScript code outside a web browser.";javascript
https://zellwk.com/blog/crud-express-mongodb/;"Is a framework for building web applications on top.
It simplifies the server creation process that is already available in Node.";javascript
NODEMON;"Nodemon restarts the server automatically when you save a file that’s used by the server.js
npm install nodemon --save-dev // insatllation as development dependency
Add this in package.json
""scripts"": {
""dev"": ""nodemon server.js""
}
now you can start nodemon with: npm run dev";javascript
is an acronym for Create, Read, Update and Delete.;"It is a set of operations we get servers to execute (POST, GET, PUT and DELETE requests respectively).
This is what each operation does:
Create (POST) - Make something
Read (GET)- Get something
Update (PUT) - Change something
Delete (DELETE)- Remove something
POST, GET, PUT, and DELETE requests let us construct Rest APIs.";javascript
to automatically download 3rd party packages;"help automate the process of downloading and upgrading libraries from a central repository
npm (starting 2015) - node package manager
yrn (starting 2016, alternative to npm - but npm packages under the hood)
bower (starting 2013 - older one, was in before npm / yarn popular)";javascript
to create a single script file;"A JavaScript module bundler is a tool that gets around the problem with a build step
(which has access to the file system) to create a final output that is browser compatible
(which doesn’t need access to the file system
browserify (starting 2011)
webpack (starting 2015)";javascript
to use future JavaScript features;"Transpiling code means converting the code in one language to code in another similar language.
for CSS eg. Sass, Less, Stylus
for JavaScript eg. babel, TypeScript, CoffeeScript (starting 2010)";javascript
to automate different parts of the build process;"For frontend development, tasks include minifying code, optimizing images, running tests, etc.
npm scripts (nowadays the most popular - use the capabilities built into the npm)
grunt, gulp (in earlier times)";javascript
Template Engines;"Pug
EJS Embedded Java Script
Nunjucks";javascript
Testing APIs in an web-applicaton;https://www.postman.com/;javascript
Embedded Javascript Template;"HTML with Javsscript logic in it
eg. for flexible li-elements from a db
<% for (let i=0; i<info.length; i++) {%>
<li class=""rapper"">
<span><%= info[i].stageName %></span>
<span><%= info[i].birthName %></span>
<span class=""del"">delete</span>
</li>
<% } %>";javascript
https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/;"curl --version => Check the installed curl version
curl https://api.github.com => show all apis from github
curl https://api.github.com/users/zellwk/repos => show all repos from a specific user (zellwk)
curl https://api.github.com/users/zellwk/repos\?sort\=pushed => show all repos with parameters (""\"" have to be before the ""="")
curl -X POST https://api.github.com/user/repos => tries to create an repo via api (use -X before the command)
curl -H ""Content-Type: application/json"" https://api.github.com -v => shows the header of the api
curl -X POST <URL> -d property1=value1 -d property2=value2 => send data via the api with the -d properties
curl -x POST -u ""username:password"" https://api.github.com/user/repos => send post-request with authentification (use -u property)";javascript
https://youtu.be/1IsL6g2ixak;"never repeat yourself / structured programming
Client (Browser,HTML,CSS,JS) => Server (Linux,Windows,PHP,Ruby,Python) => Database (MySQL,PostgresQL,NoSQL,MongoDB)
View is the Client (only thing the user sees, speaks only with controller, manly html and css)
Controller is the Server (processes requests, server-side logic, middle man between view and model)
Model is the Database (Adding/Retrieving from or to the database, speaks only with the controller)";javascript
Setting up the project;"mkdir api-project // make new directory for project
cd api-project // change directory to the project
npm init // initzialize npm project / npm-environment
npm install express // install express
npm install mongodb/ // install mongodb/
npm install ejs // install ejs";javascript
Setup Server / Middleware;"const express = require('express')
const app = express()
const MongoClient = require('mongodb').MongoClient
const PORT = 2121 // define port for localhost-access
require('dotenv').config()
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())";javascript
"store the critical credentials info in a sepearte file called "".env""";"// make an "".env"" file where the DB-string is stored - and add .env to the .gitignore so the file get not public on github later
DB_STRING = mongodb+srv://<Username from Database Access>:<Password for that user>@cluster0.ram23.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
// define basis for db-connection
let db,
dbConnectionStr = process.env.DB_STRING,
dbName = 'rap'
// connect to mongoDB (with error handling)
MongoClient.connect(dbConnectionStr, { useUnifiedTopology: true })
.then(client => {
console.log(`Connected to ${dbName} Database`)
db = client.db(dbName)
})
.catch(err =>{
console.log(`Connection to db not possible - error ${err}`)
})";javascript
process.env.PORT for Heroku-Access and PORT for localhost-access;"app.listen(process.env.PORT || PORT, ()=> {
console.log(`Server running on port ${PORT}`)
})";javascript
(4) index.ejs: spits out the actual html;"app.get('/',(request, response)=>{
db.collection('rappers').find().sort({likes: -1}).toArray()
.then(data => {
response.render('index.ejs', { info: data })
})
.catch(error => console.error(error))
})";javascript
"(4) main.js: call the method ""/"" again to update the index.ejs with GET";"app.post('/addRapper', (request, response) => {
db.collection('rappers').insertOne({stageName: request.body.stageName,
birthName: request.body.birthName, likes: 0})
.then(result => {
console.log('Rapper Added')
response.redirect('/')
})
.catch(error => console.error(error))
})";javascript
(5) main.js: awaits the response and reloads the page - so the updated data can be seen;"app.put('/addOneLike', (request, response) => {
db.collection('rappers').updateOne({stageName: request.body.stageNameS, birthName: request.body.birthNameS,likes: request.body.likesS},{
$set: {
likes:request.body.likesS + 1
}
},{
sort: {_id: -1},
upsert: true
})
.then(result => {
console.log('Added One Like')
response.json('Like Added')
})
.catch(error => console.error(error))
})";javascript
(1)-(5): same as the PUT example only with the methode DELETE;"app.delete('/deleteRapper', (request, response) => {
db.collection('rappers').deleteOne({stageName: request.body.stageNameS})
.then(result => {
console.log('Rapper Deleted')
response.json('Rapper Deleted')
})
.catch(error => console.error(error))
})";javascript
in the second part are the form fields for adding new rappers on the html-page;"// Show current rappers
<h1>Current Rappers</h1>
<ul class=""rappers"">
<% for(let i=0; i < info.length; i++) {%>
<li class=""rapper"">
<span><%= info[i].stageName %></span>
<span><%= info[i].birthName %></span>
<span><%= info[i].likes %></span>
<span class='fa fa-thumbs-up'></span>
<span class='fa fa-trash'></span>
</li>
<% } %>
</ul>
// Add a rapper
<h2>Add A Rapper:</h2>
<form action=""/addRapper"" method=""POST"">
<input type=""text"" placeholder=""Stage Name"" name=""stageName"">
<input type=""text"" placeholder=""Birth Name"" name=""birthName"">
<input type=""submit"">
</form>";javascript
3rd Part: Updating the likes / +1 like;"// AdventListener for all trash and thumbs-up icons
const deleteText = document.querySelectorAll('.fa-trash')
const thumbText = document.querySelectorAll('.fa-thumbs-up')
Array.from(deleteText).forEach((element)=>{
element.addEventListener('click', deleteRapper)
})
Array.from(thumbText).forEach((element)=>{
element.addEventListener('click', addLike)
})
// Function for handling deleting locally
// Read the stageName and birthName for the element which should be deleted
// and handover this information to the API (server.js)
// Finally reload the index.ejs with ""location.reload()""
async function deleteRapper(){
const sName = this.parentNode.childNodes[1].innerText
const bName = this.parentNode.childNodes[3].innerText
try{
const response = await fetch('deleteRapper', {
method: 'delete',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'stageNameS': sName,
'birthNameS': bName
})
})
const data = await response.json()
console.log(data)
location.reload()
}catch(err){
console.log(err)
}
}
// Function for handling a +1 like
// Read the stageName and birthName for the element which should be +1 liked
// and handover this information to the API (server.js)
// Finally reload the index.ejs with ""location.reload()""
async function addLike(){
const sName = this.parentNode.childNodes[1].innerText
const bName = this.parentNode.childNodes[3].innerText
const tLikes = Number(this.parentNode.childNodes[5].innerText)
try{
const response = await fetch('addOneLike', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'stageNameS': sName,
'birthNameS': bName,
'likesS': tLikes
})
})
const data = await response.json()
console.log(data)
location.reload()
}catch(err){
console.log(err)
}
}";javascript
3rd Part: Updating the likes / +1 like;"Keys to provide in the config.js
clientID: in Azure Active Directory => App registration => take the id
clientSecret: in the App-Registrierung => Certificates & secrets => take the value
=> in Azure Active Directory
- in App registrations
- New registration and give name eg. TestBlablabla
- choose ""in any organizational directory AND personal microsoft accounts""
- register
- copy application client-id to in config.js at client-id
=> in the registered Application and in Authentication
- redirect uri: http://localhost:2121/auth/openid/return from config.js
- front-chanell logout URL: https://localhost:2121
- check ID tokens checkbox
=> in the registered Application and in Certificates & secrets
- new client secret
- enter description and expires
- copy the value (not id!) in config.js at client-secret";javascript
create an executable (for all plattforms and standard node-version);pkg nameOfFile.js;javascript
create exe with specific node-version for windows;pkg scrapeAppStore.js --targets node12-win-x64;javascript
Hosting APIs in the cloud;"// Initial setup
git init (when .git is not in the folder of the api)
echo '{}' > composer.json // for PHP: additional when deploying an PHP-api
echo ""web: node server.js"" > Procfile // for Express: create profile (tells heroku what the server-file is)
git add .
git commit -m ""upd""
heroku login -i // login to heroku
heroku create simple-rap-api // create entry on heroku
heroku git:remote -a simple-rap-api // name of the app on heroku
git push heroku master // push everything to heroku (or git push heroku main)
set config vars in heroku under <seetings> in the app
// Ongoing updates
git add .
git commit -m ""upd""
heroku login -i
heroku git:remote -a financerapidapi
git push heroku main (or git push heroku master)";javascript