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.
<header>
<h1>DOM move detection</h1>
<p>
This shows off using <code>IntersectionObserver</code> to track movement.
<strong>Try dragging the gif, and scrolling the page!</strong>
The bounding box is invalidated and recreated only through an unrelated callback, and has no knowledge of the dragging code (and it's slowed down for this demo).
See <a target="_blank" href="https://whistlr.info/2021/observing-dom/">Observing rendered DOM nodes</a> for how!
</p>
<div id="info"></div>
</header>
<div id="vizHolder">
<div id="gifViz" class="viz"></div>
</div>
<img id="gif" src="https://storage.googleapis.com/hwhistlr.appspot.com/assets/thinking-face.gif" width="128" height="128" />
body {
font-family: Segoe UI,system-ui,-apple-system,sans-serif;
font-size: 12px;
line-height: 20px;
position: relative;
margin: 0;
min-height: calc(100vh + 64px);
}
* {
margin: 0;
}
#info {
font-family: monospace;
}
.viz {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
z-index: -1;
color: blue;
}
.viz.invalid {
color: red;
}
.viz::before,
.viz::after {
position: absolute;
border: 2px solid currentColor;
box-sizing: border-box;
content: '';
}
.viz::before {
top: -100vh;
bottom: -100vh;
left: -2px;
width: calc(100% + 4px);
}
.viz::after {
left: -100vw;
right: -100vw;
top: -2px;
height: calc(100% + 4px);
}
header {
position: fixed;
top: 0;
left: 0;
right: 0;
padding: 8px;
background: #eeee;
border-bottom: 4px solid #ccc9;
z-index: 10;
}
p {
margin: 8px 0;
}
#vizHolder {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
}
#gif {
position: absolute;
user-select: none;
left: 128px;
bottom: 128px;
}
// watcher.js clone (see https://gist.github.com/samthor/37a8555218e8a69ebf9f1eaf20f751db)
const debug = false;
const root = document.documentElement;
/** @type {Set<() => void>)} */
const activeObservers = new Set();
const documentResizeObserver = new ResizeObserver((entries) => {
activeObservers.forEach((handler) => handler());
});
documentResizeObserver.observe(root);
/**
* @param {Element} element to observe
* @param {(rect: {x: number, y: number, width: number, height: number}) => void} callback on move or resize
* @param {(ratio: number, force?: true) => void} callbackRatio for debugging
* @return {() => void} cleanup function
*/
function vizObserver(element, callback, callbackRatio) {
/** @type {IntersectionObserver?} */
let io = null;
const viz = document.createElement('div');
viz.className = 'viz';
debug && document.body.append(viz);
let refresh = (threshold = 1.0) => {
io?.disconnect();
io = null;
const rect = element.getBoundingClientRect();
const se = /** @type {HTMLElement} */ (document.scrollingElement);
const top = rect.top + se.scrollTop;
const left = rect.left + se.scrollLeft;
if (!rect.width || !rect.height) {
callback({x: 0, y: 0, width: 0, height: 0})
return; // Wait for the element to be resized to a sensible size.
}
callback({
x: left,
y: top,
width: rect.width,
height: rect.height,
});
// Calculate the exact position this element holds on the page.
const x = (v) => Math.floor(v);
const {offsetWidth: dw, offsetHeight: dh} = root;
const insetTop = x(top);
const insetLeft = x(left);
const insetRight = x(dw - (left + rect.width));
const insetBottom = x(dh - (top + rect.height));
const rootMargin = `${-insetTop}px ${-insetRight}px ${-insetBottom}px ${-insetLeft}px`;
const options = {root, rootMargin, threshold};
let isFirstUpdate = true;
callbackRatio(threshold, true);
io = new IntersectionObserver((entries) => {
const only = entries[0];
debug && console.warn('got update', only.intersectionRatio, 'first?', isFirstUpdate, 'refresh', threshold !== only.intersectionRatio);
callbackRatio(only.intersectionRatio);
if (threshold !== only.intersectionRatio) {
if (!isFirstUpdate) {
return refresh();
}
// It's possible for the watched element to not be at perfect 1.0 visibility when we create
// the IntersectionObserver. This has a couple of causes:
// - elements being on partial pixels
// - elements being hidden offscreen (e.g., <html> has `overflow: hidden`)
// - delays: if your DOM change occurs due to e.g., page resize, you can see elements
// behind their actual position
//
// In all of these cases, refresh but with this lower ratio of threshold. When the element
// moves beneath _that_ new value, the user will get notified.
let update = only.intersectionRatio;
if (update === 0.0) {
update = 0.0000001; // just needs to be non-zero
}
refresh(update);
}
isFirstUpdate = false;
}, options);
debug && console.debug('watching', {element, rootMargin, threshold});
io.observe(element);
viz.style.margin = `${insetTop}px ${insetRight}px ${insetBottom}px ${insetLeft}px`;
};
activeObservers.add(refresh);
refresh();
// Always add a ResizeObserver. This does nothing but force a refresh of the
// IntersectionObserver, since the element has now changed size.
const ro = new ResizeObserver(() => refresh());
ro.observe(element);
return () => {
ro.disconnect();
activeObservers.delete(refresh);
io?.disconnect();
};
}
// demo code
(function() {
/**
* @param {HTMLElement} element
* @param {DOMRect} rect
*/
function updatePosition(element, rect) {
const top = Math.floor(rect.y);
const left = Math.floor(rect.x);
const width = Math.ceil(rect.x + rect.width) - left;
const height = Math.ceil(rect.y + rect.height) - top;
element.style.top = `${top}px`;
element.style.left = `${left}px`;
element.style.width = `${width}px`;
element.style.height = `${height}px`;
}
let usedThreshold = 1.0;
let lastRect = {x: 0, y: 0, width: 0, height: 0};
const doUpdate = () => {
updatePosition(gifViz, lastRect);
};
const updateWithRatio = (ratio = 1.0) => {
info.textContent = `intersectionRatio=${ratio.toFixed(4)}`;
};
const initWithin = performance.now() + 100;
let updateId = 0;
const cleanup = vizObserver(gif, (rect) => {
lastRect = rect;
window.clearTimeout(updateId);
if (performance.now() < initWithin) {
return doUpdate();
}
gifViz.classList.add('invalid');
updateId = window.setTimeout(() => {
updateId = 0;
gifViz.classList.remove('invalid');
updateWithRatio(usedThreshold);
doUpdate();
}, 1000);
}, (ratio, force) => {
if (force) {
usedThreshold = ratio;
} else if (updateId === 0) {
updateWithRatio(ratio);
}
});
const eventHandler = (event) => {
if (!(event.buttons & 1)) {
return;
}
document.body.addEventListener('pointermove', eventHandler);
gif.style.top = `${event.pageY - 64}px`;
gif.style.left = `${event.pageX - 64}px`;
};
gif.addEventListener('pointermove', eventHandler);
gif.addEventListener('pointerdown', eventHandler);
document.body.addEventListener('pointerup', (event) => document.body.removeEventListener('pointermove', eventHandler));
gif.addEventListener('dragstart', (event) => event.preventDefault());
}());
Also see: Tab Triggers