Good day, friends!
In this article, I want to share with you some of the snippets that I use in my work.
It assumes you have some JavaScript programming experience.
1. How can I hide all elements of a certain type?
//
const findAll = (parent, selector) => parent.querySelectorAll(selector)
const hide = (...els) => [...els].forEach(el => el.style.display = 'none')
//
hide(findAll(document, 'img')) // "img"
2. How can I check that an element has a certain class?
//
const findOne = (parent, selector) => parent.querySelector(selector)
const hasClass = (el, className) => el.classList.contains(className)
//
hasClass(findOne(document, 'p'), 'special') // true
3. How to switch element classes?
const toggleClass = (el, className) => el.classList.toggleClass(className)
//
toggleClass(findOne(document, 'p'), 'special') // "special"
4. How to get the amount of scrolling of the current page?
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
})
//
getScrollPosition() // { x: 0, y: 200 }
5. ?
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop
if (c > 0) {
requestAnimationFrame(scrollToTop)
scrollTo(0, c - c / 8)
}
}
//
scrollTo({
top: 0,
behavior: 'smooth'
})
//
scrollToTop()
6. , ?
const elementContains = (parent, child) => parent !== child && parent.contains(child)
//
elementContains(findOne(document, 'head'), findOne(document, 'title')) // true
elementContains(findOne(document, 'body'), findOne(document, 'body')) // false
7. , ?
const elemIsVidibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect()
const { innerHeight, innerWidth } = window
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth || right > 0 && right < innerWidth))
: top >= 0 & left >=0 && bottom <= innerHeight && rigth <= innerWidth
}
//
elemIsVidibleInViewport(el) //
elemIsVidibleInViewport(el, true) //
8. , ?
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'))
return includeDuplicates ? images : [...new Set(images)]
}
//
getImages(document, true) //
getImages(document, false) //
9. ?
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop'
// Example
detectDeviceType()
11. , URL?
const getURLParams = url => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
)
//
getURLParams('http://url.com/page?f=John&l=Smith') // { f: 'John', l: 'Smith' }
getURLParams('https://google.com') // { }
12. ?
const formToObject = form =>
Array.from(new FormData(form)).reduce(
(acc, [key, value]) => ({
...acc,
[key]: value
}),
{}
)
//
formToObject(findOne(document, 'form')) // { name: 'John', email: "myemail@example.com" }
13. ?
const getProps = (from, ...selectors) =>
[...selectors].map(s =>
s
.replace(/\[([^\[\]]*)\]/g, '.$1.')
.split('.')
.filter(t => t !== '')
.reduce((prev, cur) => prev && prev[cur], from)
)
const obj = { selector: { to: { value: 'value to select' } }, target: [ 1, 2, { a: 'test' } ] }
//
getProps(obj, 'selector.to.value', 'target[0]', 'target[2].a') // [ 'value to select', 1, 'test' ]
14. ( )?
//
const log = (value) => console.log(value)
const delay = (fn, wait, ...rest) => setTimeout(fn, wait, ...rest)
//
delay(
text => log(text),
1000,
''
)
// '' 1
16. , ?
//
const addListener = (el, evt, cb) => el.addEventListener(evt, cb)
const removeListener = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts)
const fn = () => log('!')
//
;((B) => {
addListener(B, 'click', fn)
removeListener(B, 'click', fn) // "!"
})(document.body)
17. ?
const formatDuration = ms => {
if (ms < 0) ms = -ms
const time = {
// ~~ = Math.floor
day: ~~(ms / 86400000),
hour: ~~(ms / 3600000) % 24,
minute: ~~(ms / 60000) % 60,
second: ~~(ms / 1000) % 60,
millisecond: ~~(ms) % 1000
}
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
.join(', ')
}
//
formatDuration(1001); // 1 second, 1 millisecond
formatDuration(34325055574); // 397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds
18. ?
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24)
//
log(
getDaysDiffBetweenDates(new Date('2020-11-01'), new Date('2020-11-09'))
) // 8
19. GET-?
// XMLHttpRequest
const httpGet = (url, cb, err = console.error) => {
const req = new XMLHttpRequest()
req.open('GET', url, true)
req.onload = () => cb(req.responseText)
req.onerror = () => err(req)
req.send()
}
httpGet(
'https://jsonplaceholder.typicode.com/posts/1',
log
) // { "userId": 1, "id": 1, "title": "some title", "body": "some text" }
// fetch
const httpGet = (url, cb, err = console.error) =>
fetch(url)
.then(response => response.json())
.then(result => cb(result))
.catch(error => err(error))
// async/await
const httpGet = async (url, cb, err = console.error) => {
try {
const response = await fetch(url);
const result = await response.json();
cb(result);
} catch (error) {
err(error)
}
}
20. POST-?
// XMLHttpsRequest
const httpPost = (url, data, cb, err = console.error) => {
const req = new XMLHttpRequest()
req.open('POST', url, true)
req.setRequestHeader('Content-Type', 'application/json')
req.onload = () => cb(req.responseText)
req.onerror = () => err(req)
req.send(data)
}
const newPost = {
userId: 1234,
title: 'foo',
body: 'bar baz qux'
}
const data = JSON.stringify(newPost)
httpPost(
'https://jsonplaceholder.typicode.com/posts',
data,
log
) // { "id": 101, "userId": 1234, "title": "foo", "body": "bar baz qux" }
// async/await
const httpPost = async (url, data, cb, err = console.error) => {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
const result = await response.json()
cb(result)
} catch (error) {
err(error)
}
}
httpPost(
'https://jsonplaceholder.typicode.com/posts',
newPost,
log
)
21. , ?
const counter = (selector, start, end, step = 1, duration = 2000) => {
let current = start,
_step = (end - start) * step < 0 ? -step : step,
timer = setInterval(() => {
current += _step
findOne(document, selector).innerHTML = current
if (current >= end) findOne(document, selector).innerHTML = end
if (current >= end) clearInterval(timer)
}, Math.abs(~~(duration / (end - start))))
return timer
}
//
counter('#some_id', 1, 1000, 5, 2000) // "some_id"
22. ?
const copyToClipboard = str => {
const el = document.createElement('textarea')
el.value = str
el.setAttribute('readonly')
el.style.position = 'absolute'
el.style.left = '-999px'
document.body.append(el)
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false
el.select()
document.execCommand('copy')
el.remove()
if (selected) {
document.getSelection().removeAllRanges()
document.getSelection().addRange(selected)
}
}
//
copyToClipboard('some text') // "some text"
I hope you found something interesting for yourself. Even more JavaScript in my application . Thank you for attention.