Skip to content

Instantly share code, notes, and snippets.

@marckris
Last active December 31, 2019 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marckris/702cbdb4f7a9d4743b32004be9d606a7 to your computer and use it in GitHub Desktop.
Save marckris/702cbdb4f7a9d4743b32004be9d606a7 to your computer and use it in GitHub Desktop.
Using SVG icons

SVG icons with custom elements:

  1. Create your icons. Boxy SVG is perfect for this. Note that this assumes a viewBox of 0,0,128,128.
  2. Save this file, say in /css/icons.svg
  3. Include the b-icon.js somewhere.
  4. You can then use <b-icon name="hamburger" color="#fff" size="64px"></b-icon> in your HTML
  5. You can easily extend this as necessary.

That's it!

customElements.define ("b-icon", class extends HTMLElement
{
static get observedAttributes ()
{
return ["name", "color", "size"]
}
_set_icon ()
{
let name = this.getAttribute ("name")
this.innerHTML = `<svg viewBox="0 0 128 128"><use xlink:href="/css/icons.svg#${name}"></use></svg>`
let color = this.getAttribute ("color") || '#555',
style = this.querySelector ("svg").style
style.fill = style.stroke = color
if (this.hasAttribute ("size")) {
let size = this.getAttribute ("size")
style.width = size
}
}
connectedCallback ()
{
this._set_icon ()
}
attributeChangedCallback (name, oldValue, newValue)
{
if (oldValue != newValue) {
switch (name) {
case "name":
case "color":
case "size":
this._set_icon ()
break
}
}
}
})
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment