init.js
Functionality for adding "initializers" to nodes in vanilla JavaScript.
A small but powerful script that implements a function Node.addInitializer
, which works kind of like addEventListener
, except that it "listens" for the creation of nodes that match a certain selector.
Table of Contents
Background
I've never been one for JavaScript frameworks, or frameworks in general for that matter; in most cases, I much prefer working in harmony with the most mature, closest-to-metal tools possible. I've done almost all of my web development throughout my life in vanilla JS, and while I definitely think it has served me well, I've always had the ever-so-slight inkling that I might be missing one simple, tiny piece of the puzzle, without which I've never been fully satisfied with my client-side code.
I think this utility is that missing piece. For me, this small script is what completes the JavaScript standard library, in under 50 source lines of code.
Install
Include init.js on your webpage within a script
tag:
<script; type="text/javascript" src="https://drive.omaitzen.com/raw/projects/init.js/init.js"></script>
Or download init.js here.
Usage
init.js adds a function to the Node
prototype called addInitializer
. This function takes in two arguments:
- The first argument is a CSS selector, as a string.
- The second argument is a function, called an "initializer", that will essentially be bound to, and called on, each of the node's descendants - present and future - when it is created, provided it matches the selector.
Examples
A simple example - print a warning to the console when an img
tag has no alt
attribute:
document.addInitializer('img:not([alt])', function() {
console.warn("Image has no alt attribute:", this);
});
Output from this will look something like:
Image has no alt attribute: <img; src="https://example.com/image.png">
When this script is run, the warning will fire on all offending images that currently exist in the document. If an image without an alt
attribute is dynamically added to the document afterwards, the warning will fire on that image as well.
Another example - add click event listeners to all list items in an unordered list to create a simple select box:
const selectBox = document.getElementById('select');
selectBox.addInitializer('li', function() {
this.addEventListener('click', () => {
for (const listItem of selectBox.querySelectorAll('li')) {
listItem.classList.remove('selected');
}
this.classList.add('selected');
});
});
Instead of a single unordered list, this can be done on all unordered lists, present and future, with a select
class:
document.addInitializer('ul.select > li', function() {
this.addEventListener('click', () => {
for (const listItem of this.parentNode.childNodes) {
listItem.classList.remove('selected');
}
this.classList.add('selected');
});
});
Contributing
N/A
License
MIT © Owen Maitzen