HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<!--Content -->
<section id="main-content" class="container row">
<div class="col-md-12">
<section class="interactive-chart">
<h2>Chart</h2>
<!-- corrected grammar to remove the extra "are" -->
<figure class="card-skin centered" style="display: none">
<figcaption>
Data Options
<select name="dataset">
<!-- Switched the order of the two datasets so that the balance transfer information shows upon pageload, due to the fact that 'Most organic traffic to this page is coming to find balance transfer information' -->
<option value="transfer" data-json='
{
"foo": {
"name": "Credit Card One",
"totals": {
"Metric One": 50,
"Metric Two": 10,
"Metric Three": 24
}
},
"bar": {
"name": "Credit Card Two",
"totals": {
"Metric One": 0,
"Metric Two": 15,
"Metric Three": 20
}
},
"buzz": {
"name": "Credit Card Three",
"totals": {
"Metric One": 45,
"Metric Two": 24,
"Metric Three": 25
}
}
}
'>Dataset 1</option>
<!-- Spelling error on line 115, need to change from "Anual" to "Annual"-->
<option value="Rewards" data-json='
{
"foo": {
"name": "Credit Card One",
"totals": {
"Metric Four": 500,
"Metric Two": 300,
"Metric Three": 100,
"Metric One": 45
}
},
"bar": {
"name": "Credit Card Two",
"totals": {
"Metric Four": 250,
"Metric Two": 300,
"Metric Three": 120,
"Metric One": 0
}
},
"buzz": {
"name": "Credit Card Three",
"totals": {
"Metric Four": 120,
"Metric Two": 225,
"Metric Three": 100,
"Metric One": 45
}
}
}
'>
Dataset 2
</option>
</select>
</figcaption>
<svg class="bar-chart" width="800" ></svg>
</figure>
</h2>
</section>
</div>
html, body {
background-color: #efefef;
padding: 0;
margin: 0;
}
header {
width: 100%;
padding: 2rem 0rem;
background-color: #07a;
border-color: #07a;
box-shadow: 0 0 2px -1px rgba(0, 0, 0, 0.12), 0 1px 1px rgba(0, 0, 0, 0.24);
}
.container {
max-width: 1240px;
margin-left: auto;
margin-right: auto;
}
#instructions.container {
background: #FFF8DC;
border: solid .25rem #E7E2D0;
border-radius: 0.3rem;
margin-top: 2rem;
padding: 2rem 3rem;
font-size: 140%;
line-height: 1.8;
small {
opacity: .6;
text-transform: uppercase;
margin: .25rem auto;
display: block;
font-weight: bold;
border-bottom: solid 1px #ddd;
}
}
#main-content.container {
background-color: #fff;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.08);
border: 1px solid #e8e8e8;
border-radius: 0.3rem;
margin-top: 2rem;
min-height: 400px;
padding: 2rem 3rem;
}
.price-pos {
color: #007711;
}
.price-neg {
color: #bb0000;
}
.bar text{
font-size:8.5px;
}
/*
using .card-skin
using .centered
using --codepen-gray
*/
const {
keys, max, values, zip,
scaleBand, scaleLinear,
select, axisBottom, axisLeft, axisTop,
format, schemeSet1,
//Changed color scheme and thus eliminated schemeCategory10 and added schemeSet1
// schemeCategory10,
} = d3
// helpers
// -------
//
const axis = (name, type='axis') => (
a[name + type.charAt(0).toUpperCase() + type.slice(1)] ?
chart.select(`.${name}.${type}`) :
chart.append('g').attr('class', `${name} ${type}`)
)
//Scale offset and padding
const scaleBarOffset = (scale, i) => scalePadding.outer(scale) + scale.step() * i
const scalePadding = {
inner: scale => Math.round(scale.paddingInner() * scale.step()),
outer: scale => Math.round(scale.paddingOuter() * scale.step())
}
//
const translate = (x, y) => (`translate(${x}, ${y})`)
// chart
// -----
//Specifics on schemeCategory10 https://github.com/d3/d3-scale-chromatic/blob/master/README.md#schemeCategory10
// const barColors = schemeCategory10
//changed barColors to schemeSet1. Specifics on schemeSet1 https://github.com/d3/d3-scale-chromatic/blob/master/README.md#schemeSet1
const barColors = schemeSet1
//define font size, height and width, and number of ticks for chart
// const font = 12, height = 330, ticks = 5, width = 400
//altered the height and width to accomodate orientation change to vertical
const font = 8, height = 400, ticks = 5, width = 330
//Define margin of chart elements
// const margin = {top: 20, right: 300, bottom: 20, left: 100, inner: 50}
//Altered margins to accomodate orientation change to vertical
const margin = {top: 20, right: 400, bottom: 20, left: 50, inner: 80}
//Assign margins to width and height of chart
let wrap = select('.bar-chart').attrs({
width: width + margin.left + margin.right,
height: height + margin.top + margin.bottom
})
//Assign class of 'chart-body' to svg 'g' grouping
let chart = wrap.append('g').attr('class', 'chart-body')
let en = {}, m = {}, a = {}
//Binding Data
const withData = (donations) => {
//console.log(values(donations));
//define the maximum values listed on the chart ticks, based on the maximum value listed in the array
const donationMax = max(values(donations), d => max(values(d.totals)))
const donationPeriods = keys(donations.foo.totals)
const donationTotals = zip(...values(donations).map(d => values(d.totals)))
const donorNames = values(donations).map(d => d.name)
//Scales - axis have been inverted to accomodate the change to vertical orientation
//const x = scaleLinear().domain([Math.round(1.1 * donationMax), 0]).range([ height,0]) // currently runs along the y axis
const x = scaleLinear().domain([0, donationMax]).range([ height,0])
// const y = scaleBand().domain(donationPeriods).rangeRound([0, width]).paddingInner(.2).paddingOuter(.2) // attempting to flip the range to have the bars start at the bottom of the chart
const yscale = scaleLinear().domain([0, donationMax]).range([ height,0])
const y = scaleBand().domain(donationPeriods).rangeRound([0, width]).paddingInner(.2).paddingOuter(.2);
const ySub = scaleBand().domain(donorNames).rangeRound([0, y.bandwidth()]).paddingInner(.25) // attempting to flip the range to have the bars start at the bottom of the chart
//defines legend margin, offset from chart and legend text
const legendLine = ySub.bandwidth(), legendMargin = scalePadding.inner(ySub)
const legendOffset = {x: width + margin.inner, y: scalePadding.outer(y)}
const legendTextX = legendOffset.x + legendLine + legendMargin
//const barTextOffset = {x: 1.4 * ySub.bandwidth(), y: -.6 * (ySub.bandwidth() - font)}
const barTextOffset = {x: 1.4 * ySub.bandwidth(), y: -.6 * (ySub.bandwidth() - font)}
//create each axis and the contents of it's ticks
//axis have been flipped to accomodate vertical orientation
const t = d3.transition().ease(d3.easeQuadInOut).duration(!en.barGroup ? 0 : 400)
a.yAxis = axis('y').transition(t).call(axisLeft().scale(x).ticks(ticks, '$s'))
// K. Changed xGrid to yGrid (and all x values to y) to remove overlaying of x-axis labels
a.yGrid = axis('y', 'grid').transition(t).call(axisLeft().scale(x).ticks(ticks).tickSize(-height).tickFormat(''))
a.xAxis = axis('x').transition(t).call(axisBottom().scale(y).tickSize(0))
//select chart including data of donation totals
let barGroup = chart.selectAll('.bar-group').data(donationTotals)
//Append the svg grouping with the class bar-group
en.barGroup = barGroup.enter().append('g').attr('class', 'bar-group')
//Define the opacity styling of the bars on the chart
en.barGroup.style('opacity', 0).transition(t).style('opacity', 1)
//merge the group together
m.barGroup = en.barGroup.merge(barGroup)
//exit transition
barGroup.exit().transition(t).style('opacity', 0).remove()
//Chart legend
let legend = chart.selectAll('.legend').data(ySub.domain())
en.legend = legend.enter().append('g').attr('class', 'legend')
.call((s) => s.append('rect') && s.append('text'))
m.legend = en.legend.merge(legend)
let [legendSwatch, legendText] = [m.legend.select('rect'), m.legend.select('text').text(d => d)]
legend.exit().remove()
//
let bar = m.barGroup.selectAll('.bar').data(d => d)
en.bar = bar.enter().append('g').attr('class', 'bar')
.call((s) => s.append('rect') && s.append('text'))
m.bar = en.bar.merge(bar)
let [barRect, barText] = [m.bar.select('rect'), m.bar.select('text')]
bar.exit().remove()
// position of the chart and legened on the page
chart.attr('transform', translate(margin.left, margin.top))
a.xAxis.attr('transform', translate(0, height))
m.barGroup.transition(t).attr('transform', (d, i) => translate(scaleBarOffset(y, i), 0)) // Translate(x,y) switch x and y translations
m.bar.transition(t).attr('transform', (d, i) => translate(scaleBarOffset(ySub, i), 1)) // Need to reposition bars at bottom of chart. Remember, (0,0) is the top left of the chart!!
m.legend.transition(t).attr('transform', (d, i) => translate(0, legendOffset.y + scaleBarOffset(ySub, i)))
//barText.transition(t).attrs({dx: barTextOffset.y, dy: barTextOffset.x, y, x: ySub.bandwidth})
barText.transition(t).attrs({dx: barTextOffset.y, dy: barTextOffset.x, y, x: ySub.bandwidth})
legendSwatch.attr('x', legendOffset.x)
legendText.transition(t).attrs({dy: barTextOffset.y, x: legendTextX, y: ySub.bandwidth})
// creates bars on chart
// en.barGroup.attr('height', y.bandwidth)
//////Switched height and width of chart bars (need to still solve inverted bar problem)
barRect.transition(t).attrs({width: ySub.bandwidth})
barRect.transition(t).attrs({height: function(d){
//console.log(yscale(d));
return height-yscale(d) ;
}
})
barRect.transition(t).attrs({'y': function(d){return yscale(d)} });
//Creates swatches on legend
legendSwatch.transition(t).attrs({width: legendLine, height: legendLine})
// styling of the bar colors
barRect.style('fill', (d, i) => barColors[i])
//Specifies number of digits used in the text next to the chart bars
barText.text(format('$.2s'))
console.log(donationMax);
barText.transition(t).attrs({'y': function(d){return yscale(d+(donationMax/10))} }); //FIXING THE Y POSITION OF THE BAR TEXT
barText.transition(t).attrs({'x': 9});
//barText.transition(t).attrs({'x': function(d){return x(d)}});
//barText.transition(t).attrs({'transform': 'rotate(-90)'});
//Assigns the same colors to the swatches in the chart legend as the colors in the bar chart using barColors
legendSwatch.style('fill', (d, i) => barColors[i])
}
// run
// ---
//select the dataset by name
let $select = $('[name=dataset]')
//parse the JSON
const data = ($option) => (JSON.parse($option.data('json')))
//enable selection of dataset via dropdown
$select.on('change', () => withData(data($select.find('option:selected'))))
//first dataset listed in HTML is the first to appear to the user
withData(data($select.find('option:first')))
//transition enabling a 500ms delay and fast fade in effect
$select.closest('figure').delay(500).fadeIn('fast')
Also see: Tab Triggers