Skip to content

Remove whitespace svg

Javascript
HTML
2 mo. ago

Paste svg to remove unnecessary whitespace.

cleanup
svg
viewBox
whitespace
remove-whitespace-svg.js
const originalSvg = document.querySelector("#originalSvg");
const newSvg = document.querySelector("#newSvg");
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
originalSvg.addEventListener("paste", async () => {
await delay(1);
const tempContainer = document.createElement("div");
tempContainer.innerHTML = originalSvg.value;
document.body.appendChild(tempContainer);
await delay(1);
const svg = tempContainer.querySelector("svg");
if (svg) {
const { x, y, width, height } = svg.getBBox();
svg.setAttribute("viewBox", `${x} ${y} ${width} ${height}`);
newSvg.value = svg.outerHTML;
}
tempContainer.remove();
});