Javascript - web development

Log X, Y coordinates on click

window.addEventListener('click', (e) => {console.log(e.clientX, e.clientY);})
        

Named Parameters (Keyword Arguments)

function myFunc({ var1=false, var2=true } = {}) {
    console.log(var1);
    console.log(var2);
}
myFunc({var1:true});
        

Document Ready Vanilla

document.addEventListener("DOMContentLoaded", function() {

});
        

User Input Validation ( Common Pattern )

// download the attached file

// full usage example

document.addEventListener("DOMContentLoaded", () => {
    let inputValidator = new ServerInputValidator({
        inputSelector : '#edit-username',
        clientSideValidators : [
            (input) => ServerInputValidator.verifyLength(input, { length : 3, message : 'Too short ( 3 characters minimum )' })
        ],
    });
});
        

Query Selector for dataset attribute

document.querySelector("[data-foo='bar']")
        

Auto update fields based on input field

Use this to bind an input to fields (commonly used for tutorials to make errors less likely)

See this example.

document.addEventListener("DOMContentLoaded", function() {
    let domainName = document.getElementById('domain-name-tls');
    domainName.addEventListener('input', (e) => {
        let updateElems = document.querySelectorAll('.domain-name-tls');
        updateElems.forEach((elem) => {
            elem.innerText = e.target.value;
        });
    });
});

# function for autogeneration

function createAutoUpdateField(identifier) {
    let elem = document.getElementById(identifier);
    elem.addEventListener('input', (e) => {
        let updateElems = document.querySelectorAll(`.${identifier}`);
        updateElems.forEach((elem) => {
            elem.innerText = e.target.value;
        });
    });
}

# function for autogeneration AND using multiple input fields that all manipulate the same thing

function createAutoUpdateFieldForMultipleEquivalentInputs(identifier) {
    let inputElems = document.querySelectorAll(`.${identifier}-input`);
    inputElems.forEach((elem) => {
        elem.addEventListener('input', (e) => {
            let updateElems = document.querySelectorAll(`.${identifier}`);
            updateElems.forEach((elem) => {
                elem.innerText = e.target.value;
            });
            inputElems.forEach((elem) => {
                if (elem != e.target) {
                    elem.value = e.target.value;
                }
            });
        });
    });
}
# youll probably want to run this on document ready as well, if utilizing any of the above
function updateInputs(identifier) {
    let inputElem = document.querySelector(`.${identifier}-input`);
    let updateElems = document.querySelectorAll(`.${identifier}`);
    updateElems.forEach((elem) => {
        elem.innerText = inputElem.value;
    });
}

        

Send form with fetch

function apiSignup(e) {
    e.preventDefault();
    fetch('http://127.0.0.1:5001/sign_up', {
        method: "POST",
        headers: {
            // 'Content-Type': 'application/json'
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(new FormData(form)).toString()
    })
        .then(res => res.json())
        .then(json => console.log(json))
        .catch(error => console.warn(error));
}
    

Set an image source to be the contents of a frame buffer

const arrayBuffer = frameBufferData;
if(urlObject){
    URL.revokeObjectURL(urlObject);
}
urlObject = URL.createObjectURL(new Blob([arrayBuffer]));
img.src = urlObject;