Skip to content

Instantly share code, notes, and snippets.

@svandragt
Last active January 3, 2024 14:53
Show Gist options
  • Save svandragt/26b49199b2d8a9d4e0a91ad0bdd8b53f to your computer and use it in GitHub Desktop.
Save svandragt/26b49199b2d8a9d4e0a91ad0bdd8b53f to your computer and use it in GitHub Desktop.
shorthand.js prototype
/**
* Returns the first element that matches the specified CSS selector within the document.
*
* @function $
* @param {string} selector - The CSS selector used to select the element.
* @returns {Element|null} The first element that matches the selector, or null if no elements are found.
*/
let $ = document.querySelector.bind(document);
/**
* Returns a collection of elements that matches the specified CSS selector(s) within the document.
*
* @param {string} selectors - CSS selector(s) to match elements against.
* @returns {NodeList} - A collection of elements that match the specified CSS selector(s).
*/
const $$ = document.querySelectorAll.bind(document)
/**
* Method used to handle event listener registration.
*
* @public
* @param {string} event - The name of the event.
* @param {function} func - The event handler function.
* @returns {Node}
*/
Node.prototype.on = HTMLDocument.prototype.on = function (event, func) {
this.addEventListener(event, func);
return this;
};
/**
* Attach a function to the 'DOMContentLoaded' event.
*
* @param {function} func - The function to be attached.
*
* @return {void}
*/
const onLoaded = func => {
document.on('DOMContentLoaded', func)
};
/**
* Cancels the default behavior and propagation of an event.
*
* @param {Event} ev - The event object to be cancelled.
*
* @return {void}
*/
function cancel(ev) {
ev.preventDefault()
ev.stopPropagation()
}
onLoaded(() => console.debug('shorthand.js loaded.'))
@svandragt
Copy link
Author

svandragt commented Jan 3, 2024

Example:

onLoaded(() => {
    const forms = $$('form.form-delete')
    forms?.forEach($form => $form.on('submit', ev => {
        cancel(ev)
        let confirmed = confirm(`Really delete status ${ev.target.dataset.id}?`)
        if (!confirmed) return
        ev.target.submit()
    }))
})
  • This code first selects all forms with the class form-delete in the document. It then loops through each form and attaches an event listener to the submit event.
  • When a form is submitted, the event listener fires and a confirmation dialog appears, asking the user if they really want to delete the status with an id fetched from the form's data attribute.
  • If the user clicks on 'Cancel' in the confirmation dialog, the cancel() function is invoked which cancels the event propagation and default form submission behavior

@svandragt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment