Skip to content

Instantly share code, notes, and snippets.

@mikenewbuild
Last active October 26, 2021 16:27
Show Gist options
  • Save mikenewbuild/742a41a52a7e8267919a2d5ae6c41a79 to your computer and use it in GitHub Desktop.
Save mikenewbuild/742a41a52a7e8267919a2d5ae6c41a79 to your computer and use it in GitHub Desktop.
Helper methods to use in Shopify themes
export function _$(selector, scope = document) {
return scope.querySelector(selector);
}
export function _$$(selector, scope = document) {
return Array.from(scope.querySelectorAll(selector));
}
export function wrap(el, wrapper) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
export function getOffset(el) {
let rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY,
};
}
export function once(fn, context) {
let result;
return () => {
if (fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
export function shopifyImgUrl(src, size) {
return src.replace(/(\.[^.]*)$/, size + "$1");
}
export function responsiveVideos() {
setVideoAspectRatio().forEach((video) => {
const width = video.parentNode.clientWidth;
video.width = width;
video.height = video.dataset.videoAspectRatio * width;
});
}
function setVideoAspectRatio() {
return videos().map((video) => {
video.dataset.videoAspectRatio = (
video.clientHeight / video.clientWidth
).toFixed(2);
return video;
});
}
function videos() {
return [
..._$$('iframe[src*="//player.vimeo.com"]'),
..._$$('iframe[src*="//www.youtube.com"]'),
];
}
export async function getHtml(url) {
const response = fetch(url);
if (!response.ok) {
throw new Error(response.status);
}
const html = await response.text();
return html;
}
export async function getJson(url) {
const response = fetch(url);
if (!response.ok) {
throw new Error(response.status);
}
const json = await response.json();
return json;
}
export async function postJson(url, data) {
const response = fetch(url, {
method: "post",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(response.status);
}
const json = await response.json();
return json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment