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 Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
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.
<div class="container"></div>
// import font(s)
@import url('https://fonts.googleapis.com/css?family=IBM+Plex+Mono|Open+Sans')
// detail root variable(s)
font = 'Open Sans', sans-serif
font-mono = 'IBM Plex Mono', monospace
color-bg = #E6E9EC
color-card = #2E2F40
color-text = #ECF5FE
*
box-sizing border-box
margin 0
padding 0
body
width 100%
font-family font
color color-text
background color-bg
.container
max-width 700px
margin 2rem auto 1rem
padding 1rem
text-transform capitalize
background color-card
box-shadow 0 1px 4px rgba(color-card, 0.5)
p
font-weight 300
text-transform uppercase
letter-spacing 0.1rem
line-height 2
&:nth-of-type(1)
border-bottom 1px solid rgba(color-text, 0.2)
display inline-block
&:nth-of-type(2)
margin 2rem 0 1rem
text-align center
svg
text
font-size 1rem
font-family font-mono
/* globals d3 */
// global variables
const globals = {
// number of data points
points: 100,
// boolean for the draggable slider
isSelected: false,
// where the slider ought to begin and its width
begin: 40,
width: 10,
// color used in the visualization
color: '#F54780'
};
// for the data create an arbitrary set of #globals.points numbers, gradually increasing in value
const data = [];
for (let i = 0; i < globals.points; i += 1) {
data.push(i / 2 + Math.floor(Math.random() * 10));
}
// HTML elements
const container = d3
.select('.container');
container
.append('h1')
.text('D3 Slider');
container
.append('p')
.text('Enhancing a line chart with a draggable element');
// paragraph detailing the average value of the selected area
// ! update the text of the strong element when the slider is dragged
const selectionElement = container
.append('p')
.text('Average in the selected area: ')
.append('strong');
// the element updated with a function, computing the average of the data points falling in the selected area
function updateSelection(beginSelection = 10, widthSelection = 10) {
// find the data points in the selection, compute the average and include it in the selected element
const selection = [...data.slice(beginSelection, beginSelection + widthSelection)];
const averageSelection = d3.sum(selection) / selection.length;
const formatSelection = d3.format('.4');
selectionElement
.text(formatSelection(averageSelection));
}
// immediately call the function with the values specified in the globals object
updateSelection(globals.begin, globals.width);
// SVG FRAME
const margin = {
top: 20,
right: 20,
bottom: 40,
left: 60
};
const width = 900 - (margin.left + margin.right);
const height = 400 - (margin.top + margin.bottom);
const containerSVG = container
.append('svg')
.attr('viewBox', `0 0 ${width + (margin.left + margin.right)} ${height + (margin.top + margin.bottom)}`);
const containerFrame = containerSVG
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
// ! for the slider, include a defs block in which to detail a linear gradient
const containerDefs = containerSVG
.insert('defs');
// SCALES
// horizontal scale based on the number of observations
const xScale = d3
.scaleLinear()
.domain([0, globals.points - 1])
.range([0, width]);
// vertical scale based on the actual values
const yScale = d3
.scaleLinear()
.domain([0, d3.max(data)])
.range([height, 0]);
// AXES
// don't show any label on the horizontal axis
const xAxis = d3
.axisBottom(xScale)
.tickSize(0)
.tickFormat('');
containerFrame
.append('g')
.attr('transform', `translate(0, ${height})`)
.call(xAxis);
// limit the number of ticks on the vertical axis
const yAxis = d3
.axisLeft(yScale)
.ticks(5)
.tickSize(0)
.tickPadding(10)
.tickFormat(d => (d !== 0 ? d : ''));
containerFrame
.append('g')
.call(yAxis);
// line function
// horizontally using the index of the data point, vertically its value
const line = d3
.line()
.x((d, i) => xScale(i))
.y(d => yScale(d));
// area function
// closely matching the line
const area = d3
.area()
.x((d, i) => xScale(i))
.y0(yScale(0))
.y1(d => yScale(d));
// path using the line function
containerFrame
.append('path')
.attr('d', line(data))
.attr('fill', 'none')
.attr('stroke', `${globals.color}aa`)
.attr('stroke-width', '3px');
// path using the area function
containerFrame
.append('path')
.attr('d', area(data))
.attr('fill', `${globals.color}11`)
.attr('stroke', 'none');
// group nesting the element(s) used for the slider
const containerSlider = containerFrame
.append('g');
// detail a linear gradient applied on a section of a rectangle used as overlay
// this linear gradient is moved programmatically depending on user input
const containerGradient = containerDefs
.append('linearGradient')
.attr('id', 'gradient');
function updateGradient(beginGradient = 10, widthGradient = 10) {
const dataGradient = [
{ offset: '0%', color: 'transparent' },
{ offset: `${beginGradient}%`, color: 'transparent' },
{ offset: `${beginGradient}%`, color: `${globals.color}55` },
{ offset: `${beginGradient + widthGradient}%`, color: `${globals.color}55` },
{ offset: `${beginGradient + widthGradient}%`, color: 'transparent' },
];
const update = containerGradient
.selectAll('stop')
.data(dataGradient);
const enter = update
.enter();
enter
.append('stop')
.attr('offset', d => d.offset)
.attr('stop-color', d => d.color);
update
.attr('offset', d => d.offset)
.attr('stop-color', d => d.color);
}
updateGradient(globals.begin, globals.width);
// handling the slider with an overlay covering the entire viz
const overlay = containerSlider
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height)
.attr('fill', 'url(#gradient)')
.style('cursor', 'move');
// when the cursor is down set the boolean to track a selection to true
// mirror this behavior when the cursor goes back up
overlay
.on('mousedown', () => {
d3.event.preventDefault();
globals.isSelected = true;
});
overlay
.on('mouseup', () => {
d3.event.preventDefault();
globals.isSelected = false;
});
// listen for a mousemove event
overlay
.on('mousemove', function () {
// if the cursor is down on the visualization proceed finding the horizontal coordinate and updating the slider's position
if (globals.isSelected) {
// find the horizontal coordinate
const mouse = d3.mouse(this);
const [xCoor] = mouse;
// compute the distance from the left edge
const x = Math.floor(xCoor / width * 100);
updateSelection(x);
updateGradient(x);
}
});
Also see: Tab Triggers