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.
<html>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="index.js"></script>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
</body>
</html>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
}
#root {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#canvas {
display: block;
max-width: 100vw;
max-height: 95vh;
}
#tooltip {
fill: #9ecae1;
}
#tooltip text {
fill: black;
}
.bar {
fill: #3182bd;
}
.bar:hover {
fill: #deebf7;
}
// Variables to set the test for the test suite
const projectName = "bar-chart";
localStorage.setItem("example_project", "D3: Bar Chart");
const dataURL =
"https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";
const aspectRatio = 19.5 / 9;
const width = 1000;
const height = width / aspectRatio;
const calcMargins = (percentValue, width, height) => {
const percent = percentValue / 100;
const heightMargin = (height * percent) / 2;
const widthMargin = (width * percent) / 2;
return {
top: heightMargin,
right: widthMargin,
bottom: heightMargin,
left: widthMargin
};
};
const marginPercent = 18;
const margins = calcMargins(marginPercent, width, height);
// Add touchstart event listener to body, so hover semi-works on mobile
d3.select("body").on("touchstart", () => {});
const svg = d3
.select("#root")
.append("svg")
.attr("id", "canvas")
.attr("viewBox", `0 0 ${width} ${height}`)
.attr("preserveAspectRatio", "xMidYMid meet");
// Create the chart area first so the tooltip is on top
const chartArea = svg
.append("g")
.attr("transform", `translate(${margins.left}, ${margins.top})`);
// tooltip implementation based on:
// https://bl.ocks.org/d3noob/a22c42db65eb00d4e369
const tooltipHeight = height / 10;
const tooltipWidth = width / 10;
const tooltipMargins = calcMargins(2.5, tooltipWidth, tooltipHeight);
const tooltipGroup = svg.append("g").attr("id", "tooltip").attr("opacity", 0);
const tooltip = tooltipGroup
.append("rect")
.attr("width", width / 10)
.attr("height", height / 10)
.attr("rx", tooltipWidth / 10);
const tooltipDateValue = tooltipGroup
.append("text")
.attr("font-size", tooltipHeight / 3)
.attr("x", tooltipWidth / 2)
.attr("y", tooltipHeight / 4)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text("Date");
const tooltipGDPValue = tooltipGroup
.append("text")
.attr("font-size", tooltipHeight / 3)
.attr("x", tooltipWidth / 2)
.attr("y", tooltipHeight / 2 + tooltipHeight / 4)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text("GDP");
const showTooltip = (data, prop, xPos) => {
tooltipGroup
.selectAll("text")
.data(data)
.join("text")
.text((d) => d);
let translateX = margins.left + (xPos - tooltipWidth) - 20;
translateX = translateX < margins.left ? margins.left : translateX;
const translateY = height / 2;
tooltipGroup
.attr("opacity", 1)
.attr("data-date", prop)
.attr("transform", `translate(${translateX}, ${translateY})`);
};
const hideTooltip = (data) => {
tooltipGroup.attr("opacity", 0);
};
const renderLabels = (labels, margins) => {
// positioning of text from:
// https://stackoverflow.com/questions/5546346/how-to-place-and-center-text-in-an-svg-rectangle
// Render the Title
const titleHeight = margins.top;
const titleWidth = width - (margins.right + margins.left);
const titleMargins = calcMargins(5, titleWidth, titleHeight);
const titleAreaX = margins.right + titleMargins.right;
const titleAreaY = titleMargins.top;
const titleAreaHeight =
titleHeight - (titleMargins.top + titleMargins.bottom);
const titleAreaWidth = titleWidth - (titleMargins.right + titleMargins.left);
svg
.append("text")
.attr("id", "title")
.attr("font-size", titleAreaHeight)
.attr("x", titleAreaX + titleAreaWidth / 2)
.attr("y", titleAreaY + titleAreaHeight / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text(labels.title);
// Render the yLabel
const yLabelHeight = height - (margins.top + margins.bottom);
const yLabelWidth = margins.left;
const yLabelMargins = calcMargins(5, yLabelWidth, yLabelHeight);
const yAreaX = yLabelMargins.left;
const yAreaY = margins.top + yLabelMargins.top;
const yAreaHeight = yLabelHeight - (yLabelMargins.top + yLabelMargins.bottom);
const yAreaWidth =
(yLabelWidth - (yLabelMargins.right + yLabelMargins.left)) / 2;
const yLabelX = yAreaX + yAreaWidth / 2;
const yLabelY = yAreaY + yAreaHeight / 2;
svg
.append("text")
.attr("id", "yLabel")
.attr("font-size", yAreaWidth / 2)
.attr("x", yLabelX)
.attr("y", yLabelY)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.attr("transform", `rotate(-90, ${yLabelX}, ${yLabelY})`)
.text(labels.yLabel);
// Render the xLabel
const xLabelHeight = margins.bottom / 2;
const xLabelWidth = width - (margins.right + margins.left);
const xLabelMargins = calcMargins(5, xLabelWidth, xLabelHeight);
const xLabelAreaX = margins.right + xLabelMargins.right;
const xLabelAreaY = height - xLabelHeight + xLabelMargins.top;
const xLabelAreaHeight =
xLabelHeight - (xLabelMargins.top + xLabelMargins.bottom);
const xLabelAreaWidth =
xLabelWidth - (xLabelMargins.right + xLabelMargins.left);
svg
.append("text")
.attr("id", "xLabel")
.attr("font-size", xLabelAreaHeight / 2)
.attr("x", xLabelAreaX + xLabelAreaWidth / 2)
.attr("y", xLabelAreaY + xLabelAreaHeight / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text(labels.xLabel);
};
const renderBarChart = (data, margins) => {
const chartHeight = height - (margins.top + margins.bottom);
const chartWidth = width - (margins.right + margins.left);
const barWidth = chartWidth / data.length;
const xValueDate = (d) => new Date(d[0]);
const xValueString = (d) => d[0];
const yValue = (d) => d[1];
const xScale = d3
.scaleTime()
.domain(d3.extent(data, xValueDate))
.range([0, chartWidth]);
const yScale = d3
.scaleLinear()
.domain([0, d3.max(data, yValue)])
.range([chartHeight, 0]);
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const xAxisX = margins.right;
const xAxisY = height - margins.bottom;
const yAxisX = margins.right;
const yAxisY = margins.top;
const xAxisArea = svg
.append("g")
.call(xAxis)
.attr("transform", `translate(${xAxisX}, ${xAxisY})`)
.attr("id", "x-axis")
.attr("font-family", "inherit")
.attr("font-size", 12);
const yAxisArea = svg
.append("g")
.call(yAxis)
.attr("transform", `translate(${yAxisX}, ${yAxisY})`)
.attr("id", "y-axis")
.attr("font-family", "inherit")
.attr("font-size", 12);
chartArea
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("data-date", xValueString)
.attr("data-gdp", yValue)
.attr("height", (d) => chartHeight - yScale(yValue(d)))
.attr("width", barWidth)
.attr("x", (d) => xScale(xValueDate(d)))
.attr("y", (d) => yScale(yValue(d)))
.on("mouseover", (d) =>
showTooltip(d, xValueString(d), xScale(xValueDate(d)))
)
.on("mouseout", (d) => hideTooltip(d));
};
fetch(dataURL)
.then((response) => response.json())
.then((json) => {
const labels = {
title: "US Gross Domestic Product",
yLabel: "GDP Value in Billions",
xLabel: `Data Source: ${json.display_url}`
};
renderLabels(labels, margins);
renderBarChart(json.data, margins);
})
.catch((err) => {
console.error(err);
});
Also see: Tab Triggers