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.
<!-- detail a single container in which to plot multiple visualizations with D3 -->
<div class="container"></div>
// import font(s)
@import url('https://fonts.googleapis.com/css?family=Fredoka+One|Open+Sans')
// detail root variable(s)
font = 'Open Sans', sans-serif
font-header = 'Fredoka One', cursive
color-text = #333
color-bg = #fff
*
box-sizing border-box
margin 0
padding 0
body
width 100%
min-height 100vh
font-family font
color color-text
// include a simple texture through a rotated rectangle (rotating it inside of the SVG crops out a noticeable part)
background url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 100 100'><rect x='10' y='10' width='80' height='80' fill='none' stroke='green' stroke-width='2px' opacity='0.07' transform='rotate(45)'/></svg>"), color-bg
background-size 100px, 100%
background-position-y -50px, 0
background-repeat repeat, no-repeat
h1, h2
font-family font-header
h1
font-size 2.5rem
letter-spacing 0.05rem
h2
text-transform uppercase
letter-spacing 0.1rem
p
line-height 2
font-size 1.1rem
.container
// cap the width of the container and center it horizontally
max-width 700px
width 85vw
margin 1rem auto
// display the visualizations one atop the other
display flex
flex-direction column
background color-bg
box-shadow 0 1px 4px rgba(color-text, 0.25)
padding 1rem
div
margin 1rem 0
svg
margin 1rem 0
#tooltip
background color-bg
padding 1rem
max-width 400px
border-radius 4px
box-shadow 0 1px 5px rgba(color-text, 0.5)
transition all 0.2s ease-out
/* globals d3 */
// detail the URL from which to fetch the relevant data
const URL = 'https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json';
// target the single container
const container = d3.select('.container');
// detail the formatting function for the thousand digit
const format = d3.format(',');
// INTRODUCTORY ELEMENTS
container
.append('h1')
.attr('class', 'title')
.text('Kickstarter Pledges');
// TOOLTIP
const tooltip = container
.append('div')
.attr('id', 'tooltip')
.style('position', 'absolute')
.style('opacity', 0)
.style('pointer-events', 'none');
// before fetching the data, as to allocate the space for each visualization
// detail HTML elements and SVG frames (these do not rely on the actual data)
// LEGEND
const legendContainer = container
.append('div')
.attr('class', 'legend');
legendContainer
.append('h2')
.attr('class', 'subtitle')
.text('Legend');
legendContainer
.append('p')
.attr('class', 'subdescription')
.text('Hover to visualize each category.');
const legendWidth = 200;
const legendHeight = 20;
// for the legend detail a simple rectangular area, to be filled with one rectangle and one text element per category
const legendSVG = legendContainer
.append('svg')
.attr('viewBox', `0, 0 ${legendWidth} ${legendHeight}`);
// for the actual visualizations include introductory html elements (in the form of heading/possibly paragraph)
// add then the SVG frame, benefiting from the same widht and height
const width = 500;
const height = 500;
// TREEMAP
const treemapContainer = container
.append('div')
.attr('class', 'viz');
treemapContainer
.append('h2')
.attr('class', 'subtitle')
.text('Treemap Diagram');
treemapContainer
.append('p')
.attr('class', 'subdescription')
.text('Hover to highlight each project, its category and amount of pledges.');
const treemapSVG = treemapContainer
.append('svg')
.attr('viewBox', `0, 0 ${width} ${height}`);
// CIRCULAR PACKING
const packingContainer = container
.append('div')
.attr('class', 'viz');
packingContainer
.append('h2')
.attr('class', 'subtitle')
.text('Circular Packing');
packingContainer
.append('p')
.attr('class', 'subdescription')
.text('Hover to highlight each project, its category and amount of pledges.');
const packingSVG = packingContainer
.append('svg')
.attr('viewBox', `0, 0 ${width} ${height}`);
/* define a function to detail SVG elements for
- legend
- viz:
- treemap
- circular packing
*/
function drawViz(data) {
// compute a hierarchy based on the JSON data
const hierarchy = d3.hierarchy(data);
// compute for each node the relative weight, through the _value_ property
hierarchy.sum(d => d.value);
// console.log(hierarchy);
// consider every node
const descendants = hierarchy.descendants();
// console.log(descendants);
// split the categories from the actual projects
const categories = descendants.filter(descendant => descendant.depth === 1);
// LEGEND
// add a group element for each category (to later nest connected rect and text elements)
// show the text element only when hovering on the rectangle elments
// when hovering also expand the rectangle being hovered
const legendGroups = legendSVG
.selectAll('g.legend')
.data(categories)
.enter()
.append('g')
.attr('class', 'legend')
.on('mouseenter', function () {
// expand the selected rectangle, contract every other one
// restore on mouseout
d3
.selectAll('g.legend rect')
.transition()
.attr('width', 0);
d3
.select(this)
.select('rect')
.transition()
.attr('x', 0)
.attr('width', legendWidth);
// introduce the text element with a small delay
d3
.select(this)
.select('text')
.transition()
.delay(200)
.style('opacity', 1);
})
.on('mouseout', function () {
d3
.selectAll('g.legend rect')
.transition()
.attr('x', (d, i) => legendWidth / categories.length * i)
.attr('width', legendWidth / categories.length);
d3
.select(this)
.select('text')
.transition()
.style('opacity', 0);
});
// add colored rectangles for each category
legendGroups
.append('rect')
.attr('x', (d, i) => legendWidth / categories.length * i)
.attr('y', 0)
.attr('width', legendWidth / categories.length)
.attr('height', legendHeight)
.attr('fill', (d, i) => `hsl(${360 / categories.length * i}, 60%, 50%)`);
// add text elements right above the rectangle elements
legendGroups
.append('text')
.attr('x', legendWidth / 15)
.attr('y', legendHeight / 2)
.text(d => d.data.name)
.attr('font-size', '0.6rem')
.attr('fill', '#fff')
.attr('alignment-baseline', 'middle')
.style('pointer-events', 'none')
.style('opacity', 0);
// TREEMAP
// define the layout function
const treemap = d3.treemap();
// format the data through the layout function
// the function adds four important values in x0, x1, y0 and y1, to describe the starting and ending point
// values in the 0-1 range
const treemapData = treemap(hierarchy);
// console.log(treemapData);
// ! it is not possible to use the same descendants as before, as those do not possess the values just included through the layout function
const descendantsTreemap = treemapData.descendants();
const categoriesTreemap = descendantsTreemap.filter(descendant => descendant.depth === 1);
const projectsTreemap = descendantsTreemap.filter(descendant => descendant.depth === 2);
// include one rectangle for each category, with a color picked from the 0-360 spectrum
treemapSVG
.selectAll('rect.category')
.data(categoriesTreemap)
.enter()
.append('rect')
.attr('class', 'category')
.attr('x', d => d.x0 * width)
.attr('y', d => d.y0 * height)
.attr('width', d => (d.x1 - d.x0) * width)
.attr('height', d => (d.y1 - d.y0) * height)
.attr('fill', (d, i) => `hsl(${360 / categories.length * i}, 60%, 50%)`);
// include one re ctangle for each project, but show only the stroke
treemapSVG
.selectAll('rect.project')
.data(projectsTreemap)
.enter()
.append('rect')
.attr('class', 'project')
.attr('x', d => d.x0 * width)
.attr('y', d => d.y0 * height)
.attr('width', d => (d.x1 - d.x0) * width)
.attr('height', d => (d.y1 - d.y0) * height)
// ! setting the fill to none causes mouse events to be fired only when crossing the stroke
.attr('fill', 'transparent')
.attr('stroke', '#33333322')
// on mousenter highlight the selected rectangle and include pertinent information in the tooltip
.on('mouseenter', function (d) {
d3.select(this)
.attr('fill', '#33333311')
.attr('stroke', '#333333aa');
tooltip
.append('p')
.text(d.data.category)
.style('font-weight', 'bold');
tooltip
.append('p')
.text(d.data.name);
tooltip
.append('p')
.text(`$ ${format(d.data.value)}`);
// retrieve the element for the tooltip, to position the same atop the cursor
const tooltipElement = tooltip.node().getBoundingClientRect();
const { height: heightElement } = tooltipElement;
tooltip
.style('opacity', 1)
.style('left', `${d3.event.pageX}px`)
.style('top', `${d3.event.pageY - heightElement}px`);
})
.on('mouseout', function () {
d3.select(this)
.attr('fill', 'transparent')
.attr('stroke', '#33333322');
tooltip
.style('opacity', 0)
.selectAll('p')
.remove();
});
// PACKING
// repeat the same logc used in the treemap
// layout function
const pack = d3.pack();
const packData = pack(hierarchy);
// packData now has x, y and r values, for the coordinates of each circle and their radii
// consider the categories and the projects repeating the same structure used for the treemap
const descendantsPack = packData.descendants();
const categoriesPack = descendantsPack.filter(descendant => descendant.depth === 1);
const projectsPack = descendantsPack.filter(descendant => descendant.depth === 2);
// instead of drawing rectangles, draw circle elements
// based on the packData values
packingSVG
.selectAll('circle.category')
.data(categoriesPack)
.enter()
.append('circle')
.attr('class', 'category')
.attr('cx', d => d.x * width)
.attr('cy', d => d.y * height)
.attr('r', d => d.r * width)
.attr('fill', (d, i) => `hsl(${360 / categories.length * i}, 60%, 50%)`);
// add the projects always as circles, but highlighting only the stroke
// on hover detail the specific values
packingSVG
.selectAll('circle.project')
.data(projectsPack)
.enter()
.append('circle')
.attr('class', 'project')
.attr('cx', d => d.x * width)
.attr('cy', d => d.y * height)
.attr('r', d => d.r * width)
.attr('fill', 'transparent')
.attr('stroke', '#33333322')
.on('mouseenter', function (d) {
d3.select(this)
.attr('fill', '#33333311')
.attr('stroke', '#333333aa');
tooltip
.append('p')
.text(d.data.category)
.style('font-weight', 'bold');
tooltip
.append('p')
.text(d.data.name);
tooltip
.append('p')
.text(`$ ${format(d.data.value)}`);
// retrieve the element for the tooltip, to position the same atop the cursor
const tooltipElement = tooltip.node().getBoundingClientRect();
const { height: heightElement } = tooltipElement;
tooltip
.style('opacity', 1)
.style('left', `${d3.event.pageX}px`)
.style('top', `${d3.event.pageY - heightElement}px`);
})
.on('mouseout', function () {
d3.select(this)
.attr('fill', 'transparent')
.attr('stroke', '#33333322');
tooltip
.style('opacity', 0)
.selectAll('p')
.remove();
});
}
// fetch data from the selected URL
// call the drawViz function to detail the legend and the different layouts
fetch(URL)
.then(res => res.json())
.then((json) => {
drawViz(json);
});
Also see: Tab Triggers