1. How to get the base URL?
const getBaseURL = url => url.replace(/[?#].*$/, '');
getBaseURL('http://url.com/page?name=Adam&surname=Smith');
2. How to check if the URL is absolute?
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
isAbsoluteURL('https://google.com');
isAbsoluteURL('ftp://www.myserver.net');
isAbsoluteURL('/foo/bar');
3. How to get URL parameters as object?
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{}
);
getURLParameters('google.com');
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
4. How to check if the element contains another element?
const elementContains = (parent, child) =>
parent !== child && parent.contains(child);
elementContains(
document.querySelector('head'),
document.querySelector('title')
);
elementContains(document.querySelector('body'), document.querySelector('body'));
5. How to get all the ancestors of the element?
const getAncestors = el => {
let ancestors = [];
while (el) {
ancestors.unshift(el);
el = el.parentNode;
}
return ancestors;
};
getAncestors(document.querySelector('nav'));
6. How to smooth-scroll element into view?
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
smoothScroll('#fooBar');
smoothScroll('.fooBar');
7. How to handle click outside the element?
const onClickOutside = (element, callback) => {
document.addEventListener('click', e => {
if (!element.contains(e.target)) callback();
});
};
onClickOutside('#my-element', () => console.log('Hello'));
8. How to generate UUID?
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
UUIDGeneratorBrowser();
9. How to get the selected text?
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
10. How to copy text to the clipboard?
const copyToClipboard = str => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};11. How to add styles to HTML element?
const addStyles = (el, styles) => Object.assign(el.style, styles);
addStyles(document.getElementById('my-element'), {
background: 'red',
color: '#ffff00',
fontSize: '3rem'
});
12. How to toggle full-screen mode?
const fullscreen = (mode = true, el = 'body') =>
mode
? document.querySelector(el).requestFullscreen()
: document.exitFullscreen();
fullscreen();
fullscreen(false);
13. How to detect if Caps lock is on?
<form>
<label for="username">Username:</label>
<input id="username" name="username">
<label for="password">Password:</label>
<input id="password" name="password" type="password">
<span id="password-message" style="display: none">Caps Lock is on</span>
</form>
const el = document.getElementById('password');
const msg = document.getElementById('password-message');
el.addEventListener('keyup', e => {
msg.style = e.getModifierState('CapsLock')
? 'display: block'
: 'display: none';
});14. How to check if the Date is valid?
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid('December 17, 1995 03:24:00');
isDateValid('1995-12-17T03:24:00');
isDateValid('1995-12-17 T03:24:00');
isDateValid('Duck');
isDateValid(1995, 11, 17);
isDateValid(1995, 11, 17, 'Duck');
isDateValid({});
15. How to get colon time from Date?
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date());
17. How to check the preferred language of the current user?
const detectLanguage = (defaultLang = 'en-US') =>
navigator.language ||
(Array.isArray(navigator.languages) && navigator.languages[0]) ||
defaultLang;
detectLanguage();
18. How to check the preferred color scheme of the user?
const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
prefersDarkColorScheme();
19. How to check if the device supports touch events?
const supportsTouchEvents = () =>
window && 'ontouchstart' in window;
supportsTouchEvents();
20. Url objects
const url = new URL("https://example.com/login?user=someguy&page=news");
url.origin
url.host
url.protocol
url.pathname
url.searchParams.get('user')
21. Dynamically Load JS Files
function loadJS(files, done) {
const head = document.getElementsByTagName('head')[0];
Promise.all(files.map(file => {
return new Promise(resolve => {
const s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = file;
s.addEventListener('load', (e) => resolve(), false);
head.appendChild(s);
});
})).then(done);
}
loadJS(["test1.js", "test2.js"], () => {
});
22. Scroll to the bottom of the page
Of course, if you know the height of the document, you can also scroll smoothly to the bottom of the page.
23. Display the element in fullscreen mode
You must have encountered such a scenario, where you need to play the video in full screen and open the page in full screen in the browser.
24. Exit browser full-screen state
Yes, this is used with the fourth point, you will also have the scenario of exiting the full-screen state of the browser.
25. Stop bubbling events
A method for preventing event bubbling that works on all platforms is necessary.
26. Determine if the device is Android or IOS
In addition to distinguishing whether it is mobile or PC, many times we also need to distinguish whether the current device is Android or IOS.
27. Get the type of browser and its version
As a front-end developer, you may encounter various compatibility issues. At this time, you may need to obtain the type and version of the browser.