Javascript
Notes #
KeyboardEvent.keycode
is deprecated, useKeyboardEvent.key
instead
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 #
element.scrollTo({
top: 100,
left: 100,
behavior: 'smooth'
})
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 #
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
}
Get Emoji Flag from Country Code #
function getFlagEmoji(countryCode) {
const codePoints = countryCode
.toUpperCase()
.split('')
.map(char => 127397 + char.charCodeAt());
return String.fromCodePoint(...codePoints);
}
Assert with console #
console.assert(1 === 1)
Format Lists with Intl.ListFormat
#
const vehicles = ['One', 'Two', 'Three'];
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
formatter.format(vehicles) // One, Two, and Three
Links #
- Introducing Astro: Ship Less JavaScript
- neilgupta/Sherlock: Natural-language event parser for Javascript
- wanasit/chrono: A natural language date parser in Javascript
- An Introduction To Stimulus.js — Smashing Magazine
- A Complete Beginner's Guide to React: Hooks Edition · We Learn Code
- WebGazer.js: Democratizing Webcam Eye Tracking on the Browser
- Vanilla JS Konami Code
- danielborowski/jsboard: JavaScript library for easily creating board games
- How to get the domain name from a URL in JavaScript – w3collective
- How can I get query string values in JavaScript?
- mark.js - JavaScript keyword highlighter
- JavaScript Event KeyCodes
- David K. 🎹 on Twitter: "🔢 Quick tip: if you're sorting an array in JS and keep forgetting how to write the compare functions (like I do), here's a mnemonic device: (a, z) => a - z // ascending, like "a to z" (a, z) => z - a // descending, like "z to a" Hope this helps someone! https://t.co/swrOZewOMC" / Twitter
- peerigon/parse-domain: Splits a hostname into subdomains, domain and (effective) top-level domains.
- FileReader.readAsDataURL() - Web APIs | MDN - image to base64
- getify/You-Dont-Know-JS: A book series on JavaScript. @YDKJS on twitter.
- Reef - A lightweight library for creating reactive, state-based UI
- Monaco Editor - VSCode editor library
- Monaco Editor in Laravel Livewire | Günther Debrauwer
- EyeDropper/color picker API
- a11y-dialog lightweight dialog/modal library
- Free Charting Library by TradingView
- Day.js · 2kB JavaScript date utility library
- SaraVieira/next-fullstack-starter: A nextjs full stack starter for your dreams
- squirm-inal Web Component Demo terminal
- Volta - The Hassle-Free JavaScript Tool Manager