Brad Woods Digital Garden

Notes / JavaScript / Cheat sheet

The Warhammer 40k Adeptus Mechanicus symbol

Table of contents

    JavaScript - cheat sheet

    Planted: 

    Status: seed

    Hits: 14

    Commonly used JavaScript patterns.

    API Reference

    • button.onclick: the drawback with inline events is that unlike event listeners, you may only have one inline event assigned
    • input.onchange: triggers on blur
    • input.oninput: triggers on keydown
    • append and prepend
    • node.parentNode.remove()
    • node.insertAdjacentHTML("afterbegin", html) is faster than node.innerHTML because it doesn't have to destroy the DOM first before inserting.
    • node.replaceChildren()
    • encodeURI(..) and decodeURI(..)
    • classList.toggle(): accepts a second paramter to control whether to add or remove the class.

    Sanitize

    Sanitizing is checking and filtering data, especially user-provided input, to remove or modify potentially harmful characters, scripts, or data that could compromise a system's security or functionality. To sanitize, use template strings to create HTML and node.textContent on any user input that needs to be set to the DOM.

    /index.js

    const todo = {
    completed: false
    }
    const userContent = "foo"
    const li = document.createElement('li')
    const html = `
    <div class="view">
    <input class="toggle" type="checkbox" ${todo.completed ? 'checked' : ''}>
    <label></label>
    <button class="destroy"></button>
    </div>
    <input class="edit">
    `
    li.insertAdjacentHTML("afterbegin", html)
    li.querySelector('label').textContent = userContent
    document.querySelector('body').append(li)

    There is also a new Trusted Types API for sanitizing generated HTML.

    Rerendering

    Render everything based on the state in the render() method. Update the DOM based on your App state, not the other way around. Split the page into components that rely on different parts of data / state. Then, rerender only the parts that need to based on a data or state change.

    /index.js

    import { gameActor } from '../index';
    const idSection = 'mySection';
    const idButton = 'myButton';
    export function render() {
    const node = document.body;
    const html = `
    <section id="${idSection}">
    <h2>Location A</h2>
    <button id="${idButton}" type="button">Leave</button>
    </section>
    `;
    node.insertAdjacentHTML('beforeend', html);
    document.querySelector(`#${idButton}`)?.addEventListener('click', () => {
    ...
    });
    }
    // We don't need to remove event listeners because node.remove() will remove them from the target element and children.
    export function derender() {
    document.querySelector(`#${idSection}`)?.remove();
    }

    Feedback

    Have any feedback about this note or just want to comment on the state of the economy?

    Where to next?

    JavaScript
    Arrow pointing downYOU ARE HERE
    A Johnny Cab pilot