-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path00_usefull-code-snippets.js
More file actions
211 lines (180 loc) · 5.48 KB
/
00_usefull-code-snippets.js
File metadata and controls
211 lines (180 loc) · 5.48 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
// Logging
console.log(); // prints a stringified representation of the argument passed in
console.dir(); // prints out a navigable tree (a full representation of an object)
// Scroll to the top of the page
const scrollToTop = () => {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
});
};
// Scroll to the bottom of the page
const scrollToBottom = () => {
window.scrollTo({
top: document.documentElement.offsetHeight,
left: 0,
behavior: 'smooth',
});
};
// Scroll elements to the visible area
const smoothScroll = (element) => {
element.scrollIntoView({
behavior: 'smooth',
});
};
// Infinite Scrolling: Basic Example
let number = 0;
const scrollHandler = () => {
const distanceToBottom = document.body.getBoundingClientRect().bottom;
const heightOfVisibleContent = document.documentElement.clientHeight;
if (distanceToBottom < heightOfVisibleContent + 150) {
const newElement = document.createElement('div');
number++;
newElement.innerHTML = `<p>Element ${number}</p>`;
document.body.append(newElement);
}
};
window.addEventListener('scroll', scrollHandler);
// Display the element in fullscreen mode
const goToFullScreen = (element) => {
element = element || document.body;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
};
// Exit browser full-screen state
const goExitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
};
// Prompt window in browser with prompt built-in function
const value = prompt('Insert your wished value.', 'test'); // "test": default value
console.log(value); // "test" or user input
// Get the type of data
const getType = (value) => {
const match = Object.prototype.toString.call(value).match(/ (\w+)]/);
return match[1].toLocaleLowerCase();
};
getType(); // undefined
getType({}); // object
getType([]); // array
getType(1); // number
getType('test'); // string
getType(true); // boolean
getType(/test/); // regexp
// Stop bubbling events
const stopPropagation = (event) => {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
};
// Deep copy an object
const deepCopy = (obj, hash = new WeakMap()) => {
if (obj instanceof Date) {
return new Date(obj);
}
if (obj instanceof RegExp) {
return new RegExp(obj);
}
if (hash.has(obj)) {
return hash.get(obj);
}
let allDesc = Object.getOwnPropertyDescriptors(obj);
let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);
hash.set(obj, cloneObj);
for (let key of Reflect.ownKeys(obj)) {
if (obj[key] && typeof obj[key] === 'object') {
cloneObj[key] = deepCopy(obj[key], hash);
} else {
cloneObj[key] = obj[key];
}
}
return cloneObj;
};
// Determining the type of device
const isMobile = () => {
return !!navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Blackberry|WebOS|Windows Phone|Phone)/i);
};
// Determine if the device is Android or IOS
const isAndroid = () => {
return /android/i.test(navigator.userAgent.toLowerCase());
};
const isIOS = () => {
let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
};
// Set cookies
const setCookie = (key, value, expire) => {
const d = new Date();
d.setDate(d.getDate() + expire);
document.cookie = `${key}=${value};expires=${d.toUTCString()}`;
};
// Get cookies
const getCookie = (key) => {
const cookieStr = unescape(document.cookie);
const arr = cookieStr.split('; ');
let cookieValue = '';
for (let i = 0; i < arr.length; i++) {
const temp = arr[i].split('=');
if (temp[0] === key) {
cookieValue = temp[1];
break;
}
}
return cookieValue;
};
// Delete cookies
const delCookie = (key) => {
document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`;
};
// Generate a random string
const randomString = (len) => {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
let strLen = chars.length;
let randomStr = '';
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
randomString(10); // pfkMfjEJ6x
randomString(20); // ce6tEx1km4idRNMtym2S
// Capitalize the first letter of the string
const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
fistLetterUpper('test'); // Test
// Generate random numbers in a specified range
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10); // 6
randomNum(10, 20); // 11
// Shuffle the order of an array
const shuffleArray = (array) => {
return array.sort(() => 0.5 - Math.random());
};
let arr = [1, -1, 10, 5];
shuffleArray(arr); // [5, -1, 10, 1]
shuffleArray(arr); // [1, 10, -1, 5]
// Get a random value from an array
const getRandomValue = (array) => array[Math.floor(Math.random() * array.length)];
const prizes = ['$100', '🍫', '🍔'];
getRandomValue(prizes); // 🍫
getRandomValue(prizes); // 🍔
getRandomValue(prizes); // 🍫