-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
376 lines (282 loc) · 7.73 KB
/
main.js
File metadata and controls
376 lines (282 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// ATTENTION: THIS IS CODE FROM THE YOUTUBE CRASH COURSE. IT IS NOT MEANT TO RUN, IT IS JUST FOR LEARNING PURPOSES //
// LOGGING OUTPUT
alert('Hello World'); // Do not use for debugging. Stops script and only strings
console.log('Hello World');
console.error('This is an error');
console.warn('This is a warning');
// VARIABLES - var, let, const
let age = 30;
// let can be re-assigned, const can not
age = 31;
// DATA TYPES - String, Number, Boolean, null, undefined
const name = 'Brad';
const age = 37;
const rating = 3.5;
const isCool = true;
const x = null;
const y = undefined;
let z; // undefined
// Check type
console.log(typeof z);
// STRINGS
// Concatenation
console.log('My name is ' + name + ' and I am ' + age);
// Template literal (better)
console.log(`My name is ${name} and I am ${age}`);
// String methods & properties
const s = 'Hello World';
let val;
// Get length
val = s.length;
// Change case
val = s.toUpperCase();
val = s.toLowerCase();
// Get sub string
val = s.substring(0, 5);
// Split into array
val = s.split('');
// ARRAYS - Store multiple values in a variable
const numbers = [1,2,3,4,5];
const fruits = ['apples', 'oranges', 'pears', 'grapes'];
console.log(numbers, fruit);
// Get one value - Arrays start at 0
console.log(fruits[1]);
// Add value
fruits[4] = 'blueberries';
// Add value using push()
fruits.push('strawberries');
// Add to beginning
fruits.unshift('mangos');
// Remove last value
fruits.pop();
// // Check if array
console.log(Array.isArray(fruits));
// // Get index
console.log(fruits.indexOf('oranges'));
// OBJECT LITERALS
const person = {
firstName: 'John',
age: 30,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '50 Main st',
city: 'Boston',
state: 'MA'
}
}
// Get single value
console.log(person.name)
// Get array value
console.log(person.hobbies[1]);
// Get embedded object
console.log(person.address.city);
// Add property
person.email = 'jdoe@gmail.com';
// Array of objects
const todos = [
{
id: 1,
text: 'Take out trash',
isComplete: false
},
{
id: 2,
text: 'Dinner with wife',
isComplete: false
},
{
id: 3,
text: 'Meeting with boss',
isComplete: true
}
];
// Get specific object value
console.log(todos[1].text);
// Format as JSON
console.log(JSON.stringify(todos));
// LOOPS
// For
for(let i = 0; i <= 10; i++){
console.log(`For Loop Number: ${i}`);
}
// While
let i = 0
while(i <= 10) {
console.log(`While Loop Number: ${i}`);
i++;
}
// Loop Through Arrays
// For Loop
for(let i = 0; i < todos.length; i++){
console.log(` Todo ${i + 1}: ${todos[i].text}`);
}
// For...of Loop
for(let todo of todos) {
console.log(todo.text);
}
// HIGH ORDER ARRAY METHODS (show prototype)
// forEach() - Loops through array
todos.forEach(function(todo, i, myTodos) {
console.log(`${i + 1}: ${todo.text}`);
console.log(myTodos);
});
// map() - Loop through and create new array
const todoTextArray = todos.map(function(todo) {
return todo.text;
});
console.log(todoTextArray);
// filter() - Returns array based on condition
const todo1 = todos.filter(function(todo) {
// Return only todos where id is 1
return todo.id === 1;
});
// CONDITIONALS
// Simple If/Else Statement
const x = 30;
if(x === 10) {
console.log('x is 10');
} else if(x > 10) {
console.log('x is greater than 10');
} else {
console.log('x is less than 10')
}
// Switch
color = 'blue';
switch(color) {
case 'red':
console.log('color is red');
case 'blue':
console.log('color is blue');
default:
console.log('color is not red or blue')
}
// Ternary operator / Shorthand if
const z = color === 'red' ? 10 : 20;
// FUNCTIONS
function greet(greeting = 'Hello', name) {
if(!name) {
// console.log(greeting);
return greeting;
} else {
// console.log(`${greeting} ${name}`);
return `${greeting} ${name}`;
}
}
// ARROW FUNCTIONS
const greet = (greeting = 'Hello', name = 'There') => `${greeting} ${name}`;
console.log(greet('Hi'));
// OOP
// Constructor Function
function Person(firstName, lastName, dob) {
// Set object properties
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob); // Set to actual date object using Date constructor
// this.getBirthYear = function(){
// return this.dob.getFullYear();
// }
// this.getFullName = function() {
// return `${this.firstName} ${this.lastName}`
// }
}
// Get Birth Year
Person.prototype.getBirthYear = function () {
return this.dob.getFullYear();
}
// Get Full Name
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`
}
// Instantiate an object from the class
const person1 = new Person('John', 'Doe', '7-8-80');
const person2 = new Person('Steve', 'Smith', '8-2-90');
console.log(person2);
// console.log(person1.getBirthYear());
// console.log(person1.getFullName());
// Built in constructors
const name = new String('Kevin');
console.log(typeof name); // Shows 'Object'
const num = new Number(5);
console.log(typeof num); // Shows 'Object'
// ES6 CLASSES
class Person {
constructor(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}
// Get Birth Year
getBirthYear() {
return this.dob.getFullYear();
}
// Get Full Name
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
const person1 = new Person('John', 'Doe', '7-8-80');
console.log(person1.getBirthYear());
// ELEMENT SELECTORS
// Single Element Selectors
console.log(document.getElementById('my-form'));
console.log(document.querySelector('.container'));
// Multiple Element Selectors
console.log(document.querySelectorAll('.item'));
console.log(document.getElementsByTagName('li'));
console.log(document.getElementsByClassName('item'));
const items = document.querySelectorAll('.item');
items.forEach((item) => console.log(item));
// MANIPULATING THE DOM
const ul = document.querySelector('.items');
// ul.remove();
// ul.lastElementChild.remove();
ul.firstElementChild.textContent = 'Hello';
ul.children[1].innerText = 'Brad';
ul.lastElementChild.innerHTML = '<h1>Hello</h1>';
const btn = document.querySelector('.btn');
// btn.style.background = 'red';
// EVENTS
// Mouse Event
btn.addEventListener('click', e => {
e.preventDefault();
console.log(e.target.className);
document.getElementById('my-form').style.background = '#ccc';
document.querySelector('body').classList.add('bg-dark');
ul.lastElementChild.innerHTML = '<h1>Changed</h1>';
});
// Keyboard Event
const nameInput = document.querySelector('#name');
nameInput.addEventListener('input', e => {
document.querySelector('.container').append(nameInput.value);
});
// USER FORM SCRIPT
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const nameInput = document.querySelector('#name');
const emailInput = document.querySelector('#email');
const msg = document.querySelector('.msg');
const userList = document.querySelector('#users');
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if(nameInput.value === '' || emailInput.value === '') {
// alert('Please enter all fields');
msg.classList.add('error');
msg.innerHTML = 'Please enter all fields';
// Remove error after 3 seconds
setTimeout(() => msg.remove(), 3000);
} else {
// Create new list item with user
const li = document.createElement('li');
// Add text node with input values
li.appendChild(document.createTextNode(`${nameInput.value}: ${emailInput.value}`));
// Add HTML
// li.innerHTML = `<strong>${nameInput.value}</strong>e: ${emailInput.value}`;
// Append to ul
userList.appendChild(li);
// Clear fields
nameInput.value = '';
emailInput.value = '';
}
}