Skip to content

Instantly share code, notes, and snippets.

@jkulton
Created February 24, 2022 02:47
Show Gist options
  • Save jkulton/9283c20876a3ad32cc4b798ca1938ffb to your computer and use it in GitHub Desktop.
Save jkulton/9283c20876a3ad32cc4b798ca1938ffb to your computer and use it in GitHub Desktop.
Swindle
(function() {
if (window.Swindle !== undefined) return;
function Swindle({
embedElementParam = 'swindle_embed',
embedURLParam = 'swindle_url',
imgStyles = { maxWidth: '100%' }
} = {}) {
// Applies an object of styles to an HTML element
function applyStyles(element, styles) {
Object.keys(styles).forEach(function(style) {
if (element.style.hasOwnProperty(style)) {
element.style[style] = styles[style];
}
});
}
// Creates an <img> element
function createImg(url, styles = {}) {
const img = document.createElement('img');
applyStyles(img, styles);
img.src = url;
return img;
}
// Remove all child nodes from a given element
function removeChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
function main() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const embedElement = urlParams.get(embedElementParam);
const imageURL = urlParams.get(embedURLParam);
if (!imageURL || !embedElement) return;
const parent = document.querySelector(embedElement);
const img = createImg(imageURL, imgStyles);
if (!parent) return;
removeChildNodes(parent);
parent.appendChild(img);
}
document.addEventListener('DOMContentLoaded', main);
}
window.Swindle = Swindle;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment