Skip to content

Instantly share code, notes, and snippets.

@andrewaguiar
Last active November 24, 2020 00:00
Show Gist options
  • Save andrewaguiar/4054405c52605ec8a2bf0e16d8867baf to your computer and use it in GitHub Desktop.
Save andrewaguiar/4054405c52605ec8a2bf0e16d8867baf to your computer and use it in GitHub Desktop.
Bunch of useful shortcuts to work with vanilla js
// Usage:
//
// ajax({
// url: 'users',
// method: 'POST',
// data: JSON.stringify(user),
// headers: {
// 'Content-Type': 'application/json',
// },
// callback: function (xhr) {
// if (xhr.status === 200) {
// alert(xhr.responseText);
// }
// }
// })
//
const ajax = function (opts) {
const url = opts.url;
const method = opts.method || 'GET';
const headers = opts.headers || {};
const callback = opts.callback;
const data = opts.data;
const xhr = new XMLHttpRequest();
xhr.open(method, url, true)
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (callback) {
callback(xhr);
}
}
};
for (const key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
xhr.send(data);
}
// Usage:
//
// $("input[type='text']")
//
const $ = function (selector) {
return document.querySelector(selector);
}
// Usage:
//
// $s("ul li")
//
const $s = function (selector) {
return document.querySelectorAll(selector);
}
// Usage:
//
// $i("buy-button")
//
const $i = function (id) {
return document.getElementById(id);
}
// Usage:
//
// $t("h1")
//
const $t = function (tagName) {
return document.getElementsByTagName(tagName);
}
// Usage:
//
// create('div', {
// 'id': 'yay',
// 'data-component': 'panel',
// 'class': ''
// })
const $create = function (tagName, attrs) {
const el = document.createElement(tagName);
if (attrs) {
for (const key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment