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 URL's added here will be added as <link>
s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.
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.
If the stylesheet 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 CSS 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.
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.
#app
*
*:after
*:before
box-sizing border-box
outline-color transparent
::selection
background transparent
body
background #3a539b
font-family 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif
margin 0
overflow hidden
padding 0
canvas
height 100vh
width 100vw
position absolute
button
$color = #26a65b
padding 8px 14px
border-radius 4px
border 0
color #fafafa
cursor pointer
background $color
outline-color transparent
&:hover
background darken($color, 20%)
&:active
background darken($color, 30%)
.time
border-left 2px dashed #fafafa
position absolute
color #fafafa
font-size 1.25rem
padding 1rem 1rem 1rem 1rem
right 0
top 0
bottom 0
.show-info
animation scaleIn .5s ease both
width 85vw
background #fafafa
padding 20px
border-radius 6px
max-height 85vh
max-width 400px
overflow auto
position absolute
top 50%
left 50%
transform translate(-50%, -50%) scale(1)
z-index 2
code
color #e74c3c
@keyframes scaleIn
from
transform translate(-50%, -50%) scale(0)
.actions
color #fafafa
position absolute
width 100vw
display grid
grid-template-rows repeat(4, 1fr)
padding-left 10px
bottom 10vh
align-items center
justify-content flex-start
.chosen-time
color #fafafa
font-size 1rem
position absolute
padding 10px
bottom 0
input[type=range]
background #3a539b
-webkit-appearance none
margin 18px 0
width 100%
outline 0
&:focus
outline none
&:focus::-moz-range-track
outline 0
&::-webkit-slider-runnable-track
width 100%
height 8px
cursor pointer
animate 0.2s
background lighten(dodgerblue, 75%)
border-radius 4px
outline 0
&::-moz-range-track
width 100%
height 8px
cursor pointer
outline 0
animate 0.2s
background lighten(dodgerblue, 75%)
border-radius 4px
&::-webkit-slider-thumb
height 20px
width 20px
border-radius 100%
background dodgerblue
cursor pointer
-webkit-appearance none
margin-top -5px
&::-moz-range-thumb
height 20px
width 20px
border-radius 100%
background dodgerblue
cursor pointer
const { moment, PIXI, PropTypes, React, ReactDOM } = window
const { Component, Fragment } = React
const { render } = ReactDOM
const { Application, Rectangle, Sprite } = PIXI
const rootNode = document.getElementById('app')
const BLOB_SIZE = 40
const DEBOUNCE = 'DEBOUNCE'
const THROTTLE = 'THROTTLE'
const TIME_FORMAT = 'hh:mm:ss'
const TIME_BASE = moment().format(TIME_FORMAT)
/**
* debounce function
* use inDebounce to maintain internal reference of timeout to clear
*/
const debounce = (func, delay) => {
let inDebounce
return function() {
const context = this
const args = arguments
clearTimeout(inDebounce)
inDebounce = setTimeout(() => func.apply(context, args), delay)
}
}
/**
* throttle function that catches and triggers last invocation
* use time to see if there is a last invocation
*/
const throttle = (func, limit) => {
let lastFunc
let lastRan
return function() {
const context = this
const args = arguments
if (!lastRan) {
func.apply(context, args)
lastRan = Date.now()
} else {
clearTimeout(lastFunc)
lastFunc = setTimeout(function() {
if (Date.now() - lastRan >= limit) {
func.apply(context, args)
lastRan = Date.now()
}
}, limit - (Date.now() - lastRan))
}
}
}
const getShape = (size, isDiamond) => {
const d = document.createElement('canvas')
const c = d.getContext('2d')
const side = Math.sqrt((size * size) / 2)
d.height = size
d.width = size
c.fillStyle = '#ffffff'
if (isDiamond) {
c.translate(size / 2, 0)
c.rotate((45 * Math.PI) / 180)
c.fillRect(0, 0, side, side)
} else {
c.arc(size / 2, size / 2, size / 2, 0, 2 * Math.PI)
c.fill()
}
return d
}
const Circle = getShape(BLOB_SIZE)
const Diamond = getShape(BLOB_SIZE, true)
class Timeline extends Component {
state = {
blobs: [],
}
static defaultProps = {
blobSize: BLOB_SIZE,
height: innerHeight,
debounceColor: 0x4ecdc4,
throttleColor: 0xf64747,
blobOpacity: 0.75,
onBlobSelect: () => {},
}
static propTypes = {
blobSize: PropTypes.number,
height: PropTypes.number,
debounceColor: PropTypes.number,
throttleColor: PropTypes.number,
blobOpacity: PropTypes.number,
onBlobSelect: PropTypes.func,
}
onTick = () => {
const {
App,
BlobContainer,
BlobTwoContainer,
state: { blobs },
props: { blobSize },
} = this
if (!blobs || !blobs.length) return
if (
App.renderer.width !== innerWidth ||
App.renderer.height !== innerHeight
) {
App.renderer.resize(innerWidth, innerHeight)
BlobContainer.removeChildren()
BlobTwoContainer.removeChildren()
this.setState({ blobs: [] })
} else {
for (const blob of blobs) {
if (blob.active) {
blob.x += 1
blob.hitArea = new Rectangle(blob.x, blob.y, blobSize, blobSize)
}
if (blob.x > innerWidth) {
blob.active = false
blob.x = -blobSize
blob.data.fresh = false
}
}
}
}
getBlob = isDebounce => {
const {
createBlob,
state: { blobs },
} = this
// Either generate a new blob or return one from state 👍
const available = blobs.find(
b => !b.active && (isDebounce ? b.type === DEBOUNCE : b.type === THROTTLE)
)
if (available) {
available.active = true
return available
} else {
return createBlob(isDebounce)
}
}
createBlob = isDebounce => {
const {
BlobContainer,
BlobTwoContainer,
props: { blobSize, debounceColor, height, throttleColor },
} = this
const Blob = new Sprite.from(isDebounce ? Circle : Diamond)
const y = Math.floor(Math.random() * (height - blobSize))
Blob.active = true
Blob.x = -blobSize
Blob.y = y
Blob.tint = isDebounce ? debounceColor : throttleColor
Blob.alpha = 1
Blob.data = {
fresh: true,
born: new Date().getTime(),
type: isDebounce ? DEBOUNCE : THROTTLE,
}
if (isDebounce) BlobContainer.addChild(Blob)
else BlobTwoContainer.addChild(Blob)
return Blob
}
showBlob = isDebounce => {
const {
getBlob,
state: { blobs: oldBlobs },
} = this
const newBlob = getBlob(isDebounce)
const blobs = newBlob.data.fresh
? [...oldBlobs, newBlob]
: oldBlobs.map(b => (b.data.born === newBlob.data.born ? newBlob : b))
this.setState({ blobs })
}
createBlobContainer = () => {
const Container = new PIXI.particles.ParticleContainer(10000, {
scale: true,
position: true,
alpha: true,
})
return Container
}
createPixiApp = () => {
const {
VIEW: view,
props: { height },
} = this
const App = new Application({
antialias: true,
height,
transparent: true,
view,
width: innerWidth,
})
return App
}
componentDidMount = () => {
const { createBlobContainer, createPixiApp, onTick } = this
const App = (this.App = createPixiApp())
const BlobContainer = (this.BlobContainer = createBlobContainer())
const BlobTwoContainer = (this.BlobTwoContainer = createBlobContainer())
App.stage.addChild(BlobContainer)
App.stage.addChild(BlobTwoContainer)
App.ticker.add(onTick)
}
render = () => {
return <canvas ref={view => (this.VIEW = view)} />
}
}
class App extends Component {
state = {
time: TIME_BASE,
debounceRate: 2000,
throttleRate: 1000,
showInfo: true,
}
showBlob = isDebounce => {
return () => {
this.TIMELINE.showBlob(isDebounce)
}
}
tick = () => {
this.setState({
time: moment().format(TIME_FORMAT),
})
}
showThrottle = throttle(this.showBlob(), this.state.throttleRate)
showDebounce = debounce(this.showBlob(true), this.state.debounceRate)
componentDidMount = () => {
window.addEventListener('mousemove', this.showDebounce)
window.addEventListener('mousemove', this.showThrottle)
window.addEventListener('touchmove', this.showDebounce)
window.addEventListener('touchmove', this.showThrottle)
this.INTERVAL = setInterval(this.tick, 1000)
}
componentWillUnmount = () => {
window.removeEventListener('mousemove', this.showDebounce)
window.removeEventListener('mousemove', this.showThrottle)
window.removeEventListener('touchmove', this.showDebounce)
window.removeEventListener('touchmove', this.showThrottle)
clearInterval(this.INTERVAL)
}
updateHandlers = debounce(() => {
const {
state: { debounceRate, throttleRate },
} = this
window.removeEventListener('mousemove', this.showDebounce)
window.removeEventListener('mousemove', this.showThrottle)
window.removeEventListener('touchmove', this.showDebounce)
window.removeEventListener('touchmove', this.showThrottle)
this.showThrottle = throttle(this.showBlob(), throttleRate)
this.showDebounce = debounce(this.showBlob(true), debounceRate)
window.addEventListener('mousemove', this.showDebounce)
window.addEventListener('mousemove', this.showThrottle)
window.addEventListener('touchmove', this.showDebounce)
window.addEventListener('touchmove', this.showThrottle)
}, 500)
onOptionChange = e => {
e.persist()
const newState = {}
newState[e.target.name] = e.target.value
this.setState(newState, () => this.updateHandlers(e.target.value))
}
discardIntro = () => {
this.setState({ showInfo: false })
}
render = () => {
const {
discardIntro,
onOptionChange,
state: { debounceRate, showInfo, throttleRate, time },
} = this
return (
<Fragment>
{showInfo && (
<div className="show-info">
<h2>What's happening here?</h2>
<p>
This demo is visualising when throttled and debounced functions
are fired.
</p>
<p>
We are throttling and debouncing <code>mousemove</code> and{' '}
<code>touchmove</code> event handling on <code>window</code>. Move
your mouse or finger around to start throttling and debouncing an
event handler. Throttled function calls are represented by a red
diamond. A debounced function call is represented by a green
circle.
</p>
<p>
You can read about throttling and debouncing in this post:{' '}
<a
rel="noopener noreferrer"
target="_blank"
href="https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf">
Throttling and Debouncing in JavaScript
</a>
</p>
<button onClick={discardIntro}>Got it! 👍</button>
</div>
)}
<div className="timeline__container">
<div className="time">{time}</div>
<Timeline ref={timeline => (this.TIMELINE = timeline)} />
</div>
<div className="actions">
<label>{`Debounce for ${debounceRate}ms`}</label>
<input
type="range"
min="50"
max="10000"
step="50"
name="debounceRate"
onChange={onOptionChange}
value={debounceRate}
/>
<label>{`Throttle every ${throttleRate}ms`}</label>
<input
type="range"
min="50"
max="10000"
step="50"
name="throttleRate"
onChange={onOptionChange}
value={throttleRate}
/>
</div>
</Fragment>
)
}
}
render(<App />, rootNode)
Also see: Tab Triggers