Skip to content

Instantly share code, notes, and snippets.

@marckris

marckris/b-icon.js

Last active Dec 31, 2019
Embed
What would you like to do?
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
}
}
}
})
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