Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="update-data">
  <button id="button">Change data</button>
  <p>(arbitrary values between 0 and 10)</p>
</div>
<label id="domain-range">
  Max value for domain range (0-20):
  <input min="0" max="20" value=10 type="range">
  <span>10</span>
</label>
<label id="domain-gap">
  tick range for domain (1-5):
  <input min="1" max="5" value=1 type="range">
  <span>1</span>
</label>
<div id="container">
  <app-bar-chart domainMin="0" domainMax="10">
    <app-bar value="2.5"></app-bar>
    <app-bar value="3.3"></app-bar>
    <app-bar value="8.3"></app-bar>
    <app-bar value="3.1"></app-bar>
    <app-bar value="7.6"></app-bar>
    <app-linear-axis domainMin="0" domainMax="10" gap="1"></app-linear-axis>
    <app-category-axis>
      <app-label>
        <!-- custom template -->
        <span>cat-1</span>
      </app-label>
      <app-label>cat-2</app-label>
      <app-label>cat-3</app-label>
      <app-label>cat-4</app-label>
      <app-label>cat-5</app-label>
    </app-category-axis>
  </app-bar-chart>
</div>
              
            
!

CSS

              
                body {
  box-sizing: border-box;
  background: #dee7e7;
  width: 100%;
  margin: 0;
  min-height: 100vh;
  display: grid;
  place-items: center;
}

body * {
  box-sizing: inherit;
}

#container {
  background: #d3e5f3;
  width: 500px;
  height: 300px;
  margin: 1em;
}

body > * {
  display: flex;
  align-items: center;
}

app-bar {
  max-width: 40px;
  transition: height 0.5s, width 0.5s;
}

app-bar::before {
  content: attr(value);
  display: grid;
  background: darkcyan;
  color: white;
  padding: 5px;
  place-items: center;
  position: relative;
  width: 40px;
  border-radius: 4px;
  border: 2px solid white;
  box-shadow: 0 0 4px 0 black;
  top: -45px;
  left: -6px;
}

app-label::part(tick) {
  width: 1px;
  height: 5px;
  background: black;
}

              
            
!

JS

              
                const button = document.getElementById("button");
const barChart = document.querySelector("app-bar-chart");
const inputRange = document.querySelector("#domain-range input[type=range]");
const inputGap = document.querySelector("#domain-gap input[type=range]");
const linearAxis = document.querySelector("app-linear-axis");

const twoDecimalOnly = (val) => Math.floor(val * 100) / 100;

button.addEventListener("click", (ev) => {
  const bars = document.querySelectorAll("app-bar");
  for (const bar of bars) {
    bar.setAttribute("value", twoDecimalOnly(Math.random() * 10));
  }
  barChart.update();
});

inputRange.addEventListener("change", () => {
  linearAxis.domainMax = inputRange.value;
  document.querySelector("#domain-range > span").textContent = inputRange.value;
});

inputGap.addEventListener("change", () => {
  linearAxis.gap = inputGap.value;
  document.querySelector("#domain-gap > span").textContent = inputGap.value;
});

/*
 ***** util.js *****
 */

const compose = (...fns) => (arg) =>
  fns.reduceRight((acc, cfn) => cfn(acc), arg);

const createScale = ({ domainMin, domainMax }) => (value) =>
  (value - domainMin) / (domainMax - domainMin);

const greaterOrEqual = (min) => (value) => Math.max(min, value);

const lowerOrEqual = (max) => (value) => Math.min(max, value);

const asPercentage = (val) => Math.floor(val * 10000) / 100; // two significative decimals

const createProjection = ({ domainMin, domainMax }) =>
  compose(
    asPercentage,
    lowerOrEqual(1),
    greaterOrEqual(0),
    createScale({ domainMin, domainMax })
  );

/*
 ***** bar.js *****
 */

class Bar extends HTMLElement {
  static get observedAttributes() {
    return ["size"];
  }

  get size() {
    return Number(this.getAttribute("size"));
  }

  set size(value) {
    this.setAttribute("size", value);
  }

  get value() {
    return Number(this.getAttribute("value"));
  }

  attributeChangedCallback() {
    this.style.setProperty("--bar-size", `${this.size}%`);
  }

  connectedCallback() {
    if (!this.hasAttribute("slot")) {
      this.setAttribute("slot", "bar-area");
    }
  }
}

customElements.define("app-bar", Bar);

/*
 ***** bar-chart.js *****
 */

const barChartTemplate = document.createElement("template");

barChartTemplate.innerHTML = `
<style>:host{
    display: grid;
    grid-template-areas:
    "axis-left bar-area"
    "bottom-left-corner axis-bottom";
    grid-template-rows: 1fr auto;
    grid-template-columns: auto 1fr;
    width:100%;
    height: 100%;
}

#bar-area{
    display:flex;
    align-items: flex-end;
    justify-content: space-around;
    grid-area: bar-area;
}

::slotted(app-bar){
    flex-grow: 1;
    height: var(--bar-size, 0%);
    background: var(--bar-color, salmon);
}

::slotted(app-category-axis){
    flex-grow: 1;
}

#axis-bottom{
    display: flex;
    grid-area: axis-bottom;
}

#axis-left{
    display: flex;
    grid-area: axis-left;
}
</style>
<div id="bar-area">
    <slot name="bar-area"></slot>
</div>
<div id="axis-left">
    <slot name="axis-left"></slot>
</div>
<div id="axis-bottom">
    <slot name="axis-bottom"></slot>
</div>
`;

class BarChart extends HTMLElement {
  static get observedAttributes() {
    return ["domainmin", "domainmax"];
  }

  get domainMin() {
    return this.hasAttribute("domainmin")
      ? Number(this.getAttribute("domainmin"))
      : Math.min(...[...this.querySelectorAll("app-bar")].map((b) => b.value));
  }

  set domainMin(val) {
    this.setAttribute("domainmin", val);
  }

  get domainMax() {
    return this.hasAttribute("domainmax")
      ? Number(this.getAttribute("domainmax"))
      : Math.max(...[...this.querySelectorAll("app-bar")].map((b) => b.value));
  }

  set domainMax(val) {
    this.setAttribute("domainmax", val);
  }

  attributeChangedCallback(...args) {
    this.update();
  }

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(barChartTemplate.content.cloneNode(true));
  }

  update() {
    console.count("update");
    const project = createProjection({
      domainMin: this.domainMin,
      domainMax: this.domainMax
    });
    const bars = this.querySelectorAll("app-bar");

    for (const bar of bars) {
      bar.size = project(bar.value);
    }
  }

  connectedCallback() {
    this.shadowRoot
      .querySelector("slot[name=bar-area]")
      .addEventListener("slotchange", () => this.update());

    this.addEventListener("domain", (ev) => {
      const { detail } = ev;
      const { domainMin, domainMax } = detail;
      this.domainMin = domainMin;
      this.domainMax = domainMax;
    });
  }
}

customElements.define("app-bar-chart", BarChart);

/*
 **** label.js ****
 */
const labelTemplate = document.createElement("template");

labelTemplate.innerHTML = `
<style>:host{
    display:flex;
}

:host([hidden]){
    display:none;
}

#label-text{
    flex-grow: 1;
    text-align: center;
}

:host(:last-child) #tick-after{
    display: none;
}

:host(:first-child) #tick-before{
    display: none;
}</style>
<div part="tick" id="tick-before"></div>
<div id="label-text"><slot></slot></div>
<div part="tick" id="tick-after"></div>
`;

class Label extends HTMLElement {
  get value() {
    return Number(this.getAttribute("value"));
  }

  set value(val) {
    if (Number.isNaN(val)) {
      this.removeAttribute("value");
    } else {
      this.setAttribute("value", val);
    }
  }

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(labelTemplate.content.cloneNode(true));
  }
}

customElements.define("app-label", Label);

/*
 ***** category-axis.js *****
 */

const categoryAxisTemplate = document.createElement("template");

categoryAxisTemplate.innerHTML = `
<style>
:host{
    display:flex;
     border-top: 1px solid gray;
}

:host([hidden]){
    display:none;
}

::slotted(app-label){
    flex-grow:1;
}

::slotted(app-label)::part(tick){
    display: inline-block;
    width: 1px;
    height: 5px;
    background: gray;
}
</style>
<slot></slot>
`;

class CategoryAxis extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(categoryAxisTemplate.content.cloneNode(true));
  }

  connectedCallback() {
    if (!this.hasAttribute("slot")) {
      this.setAttribute("slot", "axis-bottom");
    }
  }
}

customElements.define("app-category-axis", CategoryAxis);

/*
linear-axis.js
*/

const linearAxisTemplate = document.createElement("template");

linearAxisTemplate.innerHTML = `
<style>
:host{
  width: 15px;
  border-right: 1px solid gray;
}

#tick-container{
    position: relative;
    height:100%;
    display:flex;
    flex-direction:column;
}

.tick{
    border-bottom: 1px solid gray;
    position: absolute;
    bottom: calc(var(--offset) - 1px);
    padding-right:5px;
    text-align:right;
    width:100%;
    box-sizing:border-box;
}
</style>
<div id="tick-container">
</div>
`;

class LinearAxis extends HTMLElement {
  static get observedAttributes() {
    return ["domainmin", "domainmax", "gap"];
  }

  get domainMin() {
    return this.hasAttribute("domainmin")
      ? Number(this.getAttribute("domainmin"))
      : void 0;
  }

  set domainMin(val) {
    this.setAttribute("domainmin", val);
  }

  get domainMax() {
    return this.hasAttribute("domainmax")
      ? Number(this.getAttribute("domainmax"))
      : void 0;
  }

  set domainMax(val) {
    this.setAttribute("domainmax", val);
  }

  get gap() {
    return this.hasAttribute("gap") ? Number(this.getAttribute("gap")) : void 0;
  }

  set gap(val) {
    this.setAttribute("gap", val);
  }

  attributeChangedCallback() {
    const { domainMin, domainMax, gap } = this;
    if (domainMin !== void 0 && domainMax !== void 0 && gap) {
      this.update();
      this.dispatchEvent(
        new CustomEvent("domain", {
          bubbles: true,
          composed: true,
          detail: {
            domainMax,
            domainMin,
            gap
          }
        })
      );
    }
  }

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(linearAxisTemplate.content.cloneNode(true));
  }

  update() {
    const { domainMin, domainMax, gap } = this;
    const project = createProjection({ domainMin, domainMax });
    const tickContainer = cleanElement(
      this.shadowRoot.getElementById("tick-container")
    );
    const fragment = [...range(domainMin, domainMax, gap)].reduce(
      (container, current) => {
        const tick = createTick(current, project(current));
        container.appendChild(tick);
        return container;
      },
      document.createDocumentFragment()
    );

    tickContainer.appendChild(fragment);
  }

  connectedCallback() {
    if (!this.hasAttribute("slot")) {
      this.setAttribute("slot", "axis-left");
    }
  }
}

function createTick(val, offset) {
  const el = document.createElement("div");
  el.classList.add("tick");
  el.textContent = val;
  el.style.setProperty("--offset", `${offset}%`);
  return el;
}

function* range(from, to, gap) {
  let i = 0;
  while ((from + i) * gap <= to) {
    yield (from + i) * gap;
    i++;
  }
}

function cleanElement(element) {
  const range = document.createRange();
  range.selectNodeContents(element);
  range.deleteContents();
  return element;
}

customElements.define("app-linear-axis", LinearAxis);

              
            
!
999px

Console