Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <main class="max-w-6xl mx-auto my-8 pb-4 pl-4 border-l-8 border-l-teal-600">
  <h2 class="text-2xl font-medium text-amber-800">Useful</h2>
  <h1 class="mb-1 text-4xl font-light text-teal-800">Setting Variables w/ <code>style: Bar Chart</code></h1>
  <p class="font-medium">Recently, I came across some HTML code that looked like this: <code>&lt;span style="--w: .5"&gt;...&lt;/span&gt;</code>. "Wow, you can use variabls in a style attribute?!?" In this pen, I experiment with using this method of updating an element's style to produce a horizontal bar chart.</p>
  
  <nav class="dataset-nav mt-12 my-1 mx-12 flex items-center gap-4">    
  </nav>
  <div class="histogram mb-12 mx-12 p-4 border border-slate-500 rounded">
    <div class="title flex flex-col md:flex-row">
      <span class="font-bold text-teal-600 flex-1">Selected Favorite Vegetables<sup><a href="#source" title="Source for the data">1</a></span>
      <span class="current-dataset font-bold">
        All Adults
      </span>
      <nav class="dataset-nav inline-flex items-center">
      </nav>
    </div>
    <div class="graph mt-6">
      <div class="gridset y-axis">
        <div class="col-start-2 col-span-12 pb-1">Popularity: Percent of people who have a positive opintion of the vegetable</div>
      </div>
      
      <div class="gridset series">
        <div class="series-label col-start-1">Potatoes</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: crimson; --w: 90%">
            <span class="sr-only">90% enjoy potatoes</span>              
          </span>
          <span class="percent" aria-hidden="true">90%</span>
        </div>        
      </div>
      
      <div class="gridset series">
        <div class="series-label col-start-1">Sweetcorn</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: plum; --w: 83%">
            <span class="sr-only">83% enjoy sweetcorn</span>             
          </span>
          <span class="percent" aria-hidden="true">83%</span>
        </div>
      </div>
      
      <div class="gridset series">
        <div class="series-label col-start-1">Carrots</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: indigo; --w: 81%">
            <span class="sr-only">81% enjoy carrots</span>
          </span>
          <span class="percent" aria-hidden="true">81%</span>
        </div>      
      </div>
      
      <div class="gridset series">
        <div class="series-label col-start-1">Cucumbers</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: coral; --w: 78%">
            <span class="sr-only">78% enjoy cucumbers</span>
          </span>
          <span class="percent" aria-hidden="true">78%</span>
        </div>      
      </div>
      
      <div class="gridset series">
        <div class="series-label col-start-1">Spinach</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: turquoise; --w: 74%">
            <span class="sr-only">74% enjoy spinach</span>
          </span>
          <span class="percent" aria-hidden="true">74%</span>
        </div>   
      </div>

      <div class="gridset series">
        <div class="series-label col-start-1">Asparagus</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: darkseagreen; --w: 70%">
            <span class="sr-only">70% enjoy asparagus</span>
          </span>
          <span class="percent" aria-hidden="true">70%</span>
        </div>   
      </div>

      <div class="gridset series">
        <div class="series-label col-start-1">Celery</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: goldenrod; --w: 69%">
            <span class="sr-only">69% enjoy celery</span>
          </span>
          <span class="percent" aria-hidden="true">69%</span>
        </div>   
      </div>

      <div class="gridset series">
        <div class="series-label col-start-1">Cauliflower</div>
        <div class="series-data col-span-11">
          <span class="data" style="--c: hotpink; --w: 63%">
            <span class="sr-only">63% enjoy cauliflower</span>
          </span>
          <span class="percent" aria-hidden="true">63%</span>
        </div>   
      </div>

         



    </div>

  </div>
  <div id="source" class="my-12">
    <div class="font-bold">Data Source</div>
    <div><a href="https://today.yougov.com/ratings/consumer/popularity/vegetables/all" target="_blank">"The Most Popular Vegetables (Q12025)" (YouGov | US)</div>
  </div>
</main>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css2?family=Lato:wght@100;300;400;700;900&display=swap');
html, body {
  font-family: "Lato", sans-serif;
  font-size: 20px;
}

.dataset-nav {
  button {
    padding: 0.2rem 0.5rem;
    border: solid 1px LightSlateGray;
    border-radius: 0.5rem;
    &.active {
      border-color: RosyBrown;
      background-color: Beige;
    }
  }
}

.histogram {
  --axis-border: solid 2px LightSlateGray;
  
  position: relative;
  z-index: 0;
  
  .y-axis {
    border-bottom: var(--axis-border);
  }
  .gridset {
    display: grid;
    grid-template-columns: repeat(12, minmax(0, 1fr));
  }
  .series-label {
    border-right: var(--axis-border);   
    font-size: 0.8rem;
  }
  .series-data {
    position: relative;
    margin: 0.2rem;
  }
  .data {
    display: inline-block;
    width: calc(var(--w, 0) - 3rem);
    height: 100%;
    background-color: var(--c, gray);
  }
  .percent {
    display: inline-block;
    font-size: 0.9rem;
    color: SlateGray;
    transform: translateY(-0.3rem);
  }
  
  
}
              
            
!

JS

              
                const datasets = [ 
  {key: 'overall', label: 'All Adults'},
  {key: 'mill', label: 'Millennials'},
  {key: 'genX', label: 'Generation X'},
  {key: 'baby', label: 'Baby Boomers'},
];
let current = datasets[0];

const data = [
  { label: 'Potatoes', 
   overall: .9, mill: .87, genX: .92, baby: .93
  },
  { label: 'Sweetcorn', 
   overall: .83, mill: .8, genX: .9, baby: .90
  },
  { label: 'Carrots', 
   overall: .81, mill: .83, genX: .81, baby: .88
  },
  { label: 'Cucumbers', 
   overall: .78, mill: .78, genX: .77, baby: .79
  },
  { label: 'Spinach', 
   overall: .74, mill: .73, genX: .74, baby: .78
  },
  { label: 'Asparagus', 
   overall: .7, mill: .73, genX: .66, baby: .72
  },
  { label: 'Celery', 
   overall: .69, mill: .67, genX: .66, baby: .75
  },
  { label: 'Cauliflower', 
   overall: .63, mill: .63, genX: .62, baby: .68
  },

];

const colors = ['crimson', 'plum', 'indigo', 'coral', 'turquoise', 'darkseagreen', 'goldenrod', 'hotpink'];


function updateSeries(element, label, percent, color) {
  percent = Math.round(percent < 1 ? percent * 100 : percent);
  const el = {
    label: element.querySelector('.series-label'),
    data: element.querySelector('.series-data .data'), 
    percent: element.querySelector('.series-data .percent'), 
  }
  
  el.label.textContent = label;
  el.data.style.setProperty('--c', color);
  el.data.style.setProperty('--w', `${percent}%`);
  el.data.innerHTML = `<span class="sr-only>${percent}% enjoy ${label}</span>"`;
  el.percent.textContent = `${percent}%`;
}

function updateGraph(key) {
  //sort a clone of the data
  const sorted = [...data.map(m => { return {...m}; })];
  sorted.sort((a,b) => b[key] - a[key]);
  
  const histogram = document.querySelector('.histogram');
  const elements = Array.from(histogram.querySelectorAll('.series'));
  for (let index=0; index<elements.length; index++) {
    const element = elements[index];
    const label = data[index].label;
    const percent = sorted.find(m => m.label === label)[key];
    const colorIndex = sorted.findIndex(m => m.label === label);
    const color = colors[colorIndex];
    
    console.log(">>>", index, {element, label, percent, colorIndex, color});
    
    //verify that the series label matches the data label
    const seriesLabel = element.querySelector('.series-label');
    const seriesData = element.querySelector('.series-data');
    if (seriesLabel?.textContent !== label || !seriesData) {
      console.warn("Unexpected series", {expected: label, found: seriesLabel.textContent});
      throw new Error("Cannot update graph");
    }
    
    updateSeries(element, label, percent, color);    
  }
}

// setup the dataset navigation buttons and their handlers //

function setupDatasetNav() {
  const el = document.querySelector('.dataset-nav');
  //clear
  while (el.firstChild) {
    el.removeChild(el.firstChild);
  }
  
  //create the label:
  const span = document.createElement('span');
  span.className = 'font-bold text-slate-500';
  span.textContent = "Pick a dataset:";
  el.appendChild(span);
  
  //create the buttons
  datasets.forEach(ds => {
    const btn = document.createElement('button');
    btn.textContent = ds.label;
    btn.dataset.key = ds.key;
    btn.addEventListener('click', () => handleDatasetChange(ds.key));
    el.appendChild(btn);
  });

  //update with current nav
  updateDatasetNav();
}

function updateDatasetNav() {
  const el = document.querySelector('.dataset-nav');   
  const buttons = Array.from(el.querySelectorAll('button'));
  buttons.forEach(b => {
    b.classList.toggle('active', b.dataset.key === current.key);
  });
}
function handleDatasetChange(key) {
  const dset = datasets.find(m => m.key === key);
  if (dset) { 
    current = dset;
    updateDatasetNav();
    updateGraph(dset.key);
  }
}

setupDatasetNav();
              
            
!
999px

Console