Javascript

Notes #

Return Item at Index with at() #

const array = ['one', 'two', 'three']
array.at(1) // two

Array.prototype.at() - JavaScript | MDN

Sorting an Array #

const myArray = [{ attr: 'z' }, { attr: 'a' }, { attr: 'q' }]

myArray.sort((a,b) => (a.attr > b.attr) ? 1 : ((b.attr > a.attr) ? -1 : 0))

Deduplicate Array #

const dupedArray = ['one', 'two', 'one']
const newDeDupedArray = [...new Set(dupedArray)]
// ['one', 'two']

Scroll Page #

scrollTo()

element.scrollTo({
top: 100,
left: 100,
behavior: 'smooth'
})

scrollIntoView()

element.scrollIntoView({ 
behavior: 'smooth',
inline: 'start'
})

Disable Scrolling #

You probably shouldn't do this in almost all cases. Source.

function disableScroll() {
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,

window.onscroll = function() {
window.scrollTo(scrollLeft, scrollTop);
};
}

function enableScroll() {
window.onscroll = () => {}
}

Detect if Page Has Scroll Bar #

window.innerHeight > document.body.offsetHeight

Get Query Params from URL #

URLSearchParams

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

Get URL Parts #

const url = new URL('https://example.com')

{
hash: "",
host: "example.com",
hostname: "example.com",
href: "https://example.com/",
origin: "https://example.com",
password: "",
pathname: "/",
port: "",
protocol: "https:",
search: "",
searchParams: URLSearchParams {},
username: ""
}

querySelectorAll Multiple Arguments #

document.querySelectorAll('p, li')

Get Parent Element #

element.closest('.class-name')

Match Regex on String #

const regex = /#/g
myString.match(regex)

// returns null or an array of matches

Get First N Elements of Array #

myArray.slice(0, size)

Replace Contents of File #

I used this when I realised it was better to have frontmatter for Eleventy than try and extract it myself.

const fs = require('fs')

const FILES = [
'path/to/file/index.md',
'path/to/file/another.md'
]

FILES.forEach(path => {
let contents = fs.readFileSync(path, 'utf-8')
const headingLine = contents.split('\n')[0]
const heading = headingLine.replace('# ', '')
const frontMatter = `---
title: ${heading}
---
`


contents = contents.replace(headingLine, frontMatter)

fs.writeFileSync(path, contents)
})

Set xlink:href of Element #

element.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', value)

Detect Dark Mode #

// returns boolean
window.matchMedia('(prefers-color-scheme: dark)').matches
window.matchMedia('(prefers-color-scheme: light)').matches
window.matchMedia('(prefers-color-scheme: no-preference)').matches

Caching #

Simple caching technique I used before I'd read the docs for the Eleventy Cache Assets plugin. Alway read the docs first.

const fs = require('fs')
const cachePath = './cache_path.json'

if (fs.existsSync(cachePath))
{
console.log('Loading data from cache')
return {
myData: JSON.parse(fs.readFileSync(cachePath, 'utf-8'))
}
}

console.log('Loading data from API')

const res = await theApiRequest()

fs.writeFileSync(cachePath, JSON.stringify(res))

return {
myData: res
}