Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active September 27, 2023 20:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cferdinandi/abecbb003693eab0c49d1cee550ccfe8 to your computer and use it in GitHub Desktop.
Save cferdinandi/abecbb003693eab0c49d1cee550ccfe8 to your computer and use it in GitHub Desktop.
13 super rad web dev tips. https://gomakethings.com/sotb/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Event Delegation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 1em auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Event Delegation</h1>
<p>
<button class="click">Click</button>
<button class="click">Click</button>
<button>DO NOT CLICK!</button>
<button>DO NOT CLICK!</button>
<button class="click">Click</button>
</p>
<script>
document.addEventListener('click', function (event) {
// If the clicked element doesn't have the .click class, ignore it
if (!event.target.matches('.click')) return;
console.log('You clicked a button');
});
</script>
</body>
</html>
// 👎 Nested if checks
function handleClick (event) {
// Make sure clicked element has the .save-data class
if (event.target.matches('.save-data')) {
// Get the value of the [data-id] attribute
let id = event.target.getAttribute('data-id');
// Make sure there's an ID
if (id) {
// Get the user token from localStorage
let token = localStorage.getItem('token');
// Make sure there's a token
if (token) {
// Save the ID to localStorage
localStorage.setItem(`${token}_${id}`, true);
}
}
}
}
// 🦄 Early return pattern
function handleClick (event) {
// Make sure clicked element has the .save-data class
if (!event.target.matches('.save-data')) return;
// Get the value of the [data-id] attribute
let id = event.target.getAttribute('data-id');
if (!id) return;
// Get the user token from localStorage
let token = localStorage.getItem('token');
if (!token) return;
// Save the ID to localStorage
localStorage.setItem(`${token}_${id}`, true);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multiple Selectors</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 1em auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Multiple Selectors</h1>
<p>
<button class="tuna">Tuna</button>
<button class="turkey">Turkey</button>
<button class="mayo">Mayo</button>
<button class="mustard">Mustard</button>
<button class="soda">Soda</button>
</p>
<script>
// Get all matches
let all = document.querySelectorAll('.tuna, .turkey, .mayo');
console.log('all', all);
// Get the first match
let first = document.querySelector('.mustard, .soda, .turkey');
console.log('first', first);
// Check for a match
let btn = document.querySelector('button');
if (btn.matches('.turkey, .mayo, .tuna')) {
console.log(`It's a match!`);``
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Data Attribute Selectors</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 1em auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Data Attribute Selectors</h1>
<p>
<button data-click="sayHi">Say Hi!</button>
<button data-click="sayBye">Say Bye</button>
</p>
<form data-submit="login">
<button>Login</button>
</form>
<script>
// Target elements by selector
let form = document.querySelector('[data-submit="login"]');
form.addEventListener('submit', function (event) {
event.preventDefault();
alert('You logged in!');
});
// Use event delegation to get the callback function
let handlers = {
sayHi () {
alert('🎉 Hello!');
},
sayBye () {
alert('👋 See you next time...')
}
};
document.addEventListener('click', function (event) {
// Get the function to run
let fn = event.target.getAttribute('data-click');
if (!fn) return;
// Run the function
handlers[fn](event);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Query String from an Object</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
let merlin = {
job: 'Wizard',
tool: 'Wand',
age: 142,
signatureSpell: 'Dancing Teacups'
};
let queryString = new URLSearchParams(merlin).toString();
console.log(queryString);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Remove Duplicates from an Array</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
let wizards = [
'Merlin',
'Ursula',
'Gandalf',
'Merlin',
'Morgana',
'Radagast',
'Ursula'
];
let deduped = Array.from(new Set(wizards));
console.log(wizards);
console.log(deduped);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random ID</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
let id = crypto.randomUUID();
console.log(id);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>True Type Checking</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
typeof []; // object
typeof {}; // object
typeof ''; // string
typeof new Date(); // object
typeof 1; // number
typeof function () {}; // function
typeof /test/i; // object
typeof true; // boolean
typeof null; // object
typeof undefined; // undefined
// returns [object Array]
Object.prototype.toString.call([]);
// A helper function
function trueTypeOf (obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
console.log(trueTypeOf([]));
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Numeric Separators</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
// let num = 1234567890987654321;
// THIS THROWS AN ERROR
// let num = 1,234,567,890,987,654,321;
// Numeric separators make big numbers easier to read
let num = 1_234_567_890_987_654_321;
let smallNum = num / 1_000_000_000;
console.log(smallNum);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Looping Over Objects</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
let merlin = {
job: 'Wizard',
tool: 'Wand',
age: 142,
signatureSpell: 'Dancing Teacups'
};
// 👎 The old way
for (let key in merlin) {
if (Object.hasOwn(merlin, key)) {
console.log(key);
console.log(merlin[key]);
}
}
// 🦄 The new way!
for (let [key, value] of Object.entries(merlin)) {
console.log(key);
console.log(value);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Object Property Shorthands</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
let name = 'Merlin';
let tool = 'wand';
let age = 142;
// 👎 The old way
let obj = {
name: name,
tool: tool,
age: age
};
// 🦄 The new way!
let obj2 = {name, tool, age};
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simpler Boolean Returns</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
// 👎 The verbose way
function isBig (num) {
if (num > 10) {
return true;
} else {
return false;
}
}
// 🦄 A simpler way
function isBig (num) {
return num > 10;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment