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.
<main>
<header>
<div>
<h1>Late-load your Codepen embed</h1>
<p>A web component to late-load Codepens. Nothing, except the optional image, is loaded until you click the component, then the asset is loaded in full and embedded into the page.</p>
</div>
</header>
<div>
<h2>Example</h2>
<!-- <button>Button</button> -->
<code-pen description="Detect click method" slug="dyKGjQv" headingtag="h3" user="2kool2" image></code-pen>
<p> If a background image is required add an "image" attribute. The small version of the codepen image is loaded, then blurred to compensate for the poor quality. It doesn't fit that accurately. Personally, I consider the image as superflous, but included for optional usage.</p>
<p>Username and codepen identifiers are added to the component as attributes.</p>
<p>An accessibile name is added via aria-labelledby pointing to the heading.</p>
<h2>Code</h2>
<p>Component comprises of a heading and a button. Upon click, the button is replaced by an iframe.</p>
<figure>
<figcaption id="HTML_component">HTML component</figcaption>
<pre class="language-html" contenteditable spellcheck="false" role="textbox" aria-multiline="true" aria-labelledby="HTML_component"><code><code-pen
description="Detect click method"
slug="dyKGjQv"
headingtag="h3"
user="2kool2"
image>
</code-pen>
</code></pre>
</figure>
<!-- <code-pen description="Detect click method" slug="dyKGjQv" headingtag="h3" user="2kool2"> -->
<!-- </code-pen> -->
<h2>More example embeds</h2>
<code-pen description="Tooltip component" slug="ZERZgox" headingtag="h2"></code-pen>
<code-pen description="Recursive dialog (modal) windows" slug="rNvovmJ" headingtag="h2"></code-pen>
<code-pen description="Grid of radio buttons" slug="bGMqGBv" headingtag="h2"></code-pen>
<code-pen description="Chris Coyler: Using mask repeats" slug="NWGpvKm" headingtag="h2" user="chriscoyler" image></code-pen>
</div>
</main>
code-pen {
/* Optional variables to pass into the component */
--cp-heading-color: var(--text);
--cp-heading-size: var(--fs-500);
--cp-heading-weight: var(--fw-bold);
--cp-border-color: var(--border);
--cp-border-image: var(--border-gradient) 1;
--cp-border-image: ;
--cp-bg: var(--bg);
--cp-btn-bg: var(--accent);
--cp-btn-bg-hover: var(--accent-hover);
--cp-btn-border: var(--bg);
--cp-btn-border-hover: var(--bg);
--cp-btn-color: var(--bg);
--cp-btn-color-hover: var(--bg);
--cp-text-size: var(--fs-400);
--cp-text-weight: normal;
}
console.clear();
const defaultUser = '2kool2';
class codePenHTML extends HTMLElement {
constructor () {
// Always call super first in constructor
// Return value from super() is a reference to this element
super();
this.attachShadow({mode: 'open'});
}
static get observedAttributes () {
return ['headingtag', 'description', 'slug', 'image', 'user'];
}
attributeChangedCallback (property, oldValue, newValue) {
// BP: handle side effects, like setting ARIA attributes here, but not element attributes
if (oldValue === newValue) return;
this[property] = newValue;
const slot = this.shadowRoot.querySelector(`[name=${property}]`);
if (slot) slot.textContent = newValue;
// console.log(property, oldValue, newValue);
if (property === 'description') {
const iframe = this.shadowRoot.querySelector(`[title="${oldValue}"]`);
iframe && iframe.setAttribute('title', newValue);
}
if (property === 'image') {
const button = this.shadowRoot.querySelector('button');
button.style.setProperty('--useBackgroundImage', '""')
}
}
connectedCallback () {
// BP: Add role, tabindex, internal state and event listeners here
this._addStyles();
this._addHTML();
}
disconnectedCallback () {
// Fires when the element is removed from the DOM
// remove event listeners
}
_fetchPenData () {
return;
// couldn't get this to work.
// wanted to fetch the title from the pen itself, rather than using an attribute.
console.log('fetching')
let url;
url = 'https://codepen.io/api/oembed/?url=https://codepen.io/2kool2/pen/dyKGjQv/&format=js&callback=data';
url = 'https://codepen.io/api/oembed/?url=https://codepen.io/2kool2/pen/dyKGjQv/&format=js';
url = 'https://codepen.io/api/oembed/?url=https://codepen.io/2kool2/pen/dyKGjQv/&format=json';
url = 'https://codepen.io/api/oembed/?url=http://codepen.io/FWeinb/pen/wjzyH&format=json'
fetch(url, {
// mode: 'cors'
}).then(function (response) {
// The API call was successful!
return response.json();
}).then(function (data) {
// This is the JSON from our response
console.log(data);
}).catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
}
_getHeadingTag () {
return this.headingtag || 'h2';
}
_getHeading () {
const tag = this._getHeadingTag();
const heading = document.createElement(tag);
heading.id = 'h-' + this.slug;
heading.setAttribute('name', 'description');
heading.textContent = this.description;
return heading;
}
_getContainer () {
const button = document.createElement('button');
button.type = 'button';
button.id = this.slug;
button.innerHTML = this.innerHTML || '<span>Click to embed Codepen</span>';
return button;
}
_addHTML () {
const data = this._fetchPenData();
const heading = this._getHeading();
this.shadowRoot.appendChild(heading);
const container = this._getContainer();
this.shadowRoot.appendChild(container);
const user = this.user || defaultUser;
const slug = this.slug;
container.addEventListener('click', event => {
const heading = this.shadowRoot.getElementById('h-' + slug);
const iframe = document.createElement('iframe');
heading && iframe.setAttribute('aria-labelledby', heading.id);
iframe.title = heading.textContent || 'Codepen embed';
iframe.src = `https://codepen.io/${user}/embed/${slug}?default-tab=result`;
iframe.width = '100%';
iframe.height = '480';
iframe.scrolling = 'no';
iframe.setAttribute('frameborder','no');
event.target.parentNode.replaceChild(iframe, event.target)
});
}
_addStyles () {
const style = document.createElement('style');
style.textContent = `
${this._getHeadingTag()} {
color: var(--cp-heading-color, canvasText);
font-size: var(--cp-heading-size, 1.5em);
font-weight: var(--cp-heading-weight, 400);
margin: var(--v-space-2, 2rem) 0 0;
}
button {
all: unset;
box-sizing: border-box;
border: 1px solid var(--cp-border-color, canvasText);
border-image: var(--cp-border-image);
cursor: pointer;
display: grid;
font-size: var(--cp-text-size, 1.5em);
font-weight: var(--cp-text-weight, 400);
min-height: 480px;
overflow: hidden;
place-content: center;
position: relative;
width: 100%;
}
iframe,
button {
background-color: var(--cp-bg, canvas);
margin: var(--v-space, 1rem) 0 0;
}
button > span {
background-color: var(--cp-btn-bg, canvas);
border: 2px solid var(--cp-btn-border, canvasText);
border-radius: 4px;
color: var(--cp-btn-color, canvasText);
display: block;
line-height: calc(2ex + 6px);
margin: 0 auto;
max-width: 70%;
outline: 2px solid transparent;
outline-offset: 10px;
padding: 16px 16px;
pointer-events: none;
text-align: center;
transition: all .3s ease-out;
z-index: 1;
}
button:is(:hover, :focus) > span {
background-color: var(--cp-btn-bg-hover, canvasText);
border-color: var(--cp-btn-border-hover, canvas);
color: var(--cp-btn-color-hover, canvas);
border-image: none;
box-shadow: 0 2px 4px rgba(0,0,0,.5);
}
button:focus > span {
outline-color: var(--FocusRing-outline-color, blue);
outline-offset: 4px;
}
button::before {
content: var(--useBackgroundImage);
background-color: var(--bg-color, canvasText);
background-image: url(https://codepen.io/${this.user}/pen/${this.slug}/image/small.png);
background-position: top center;
background-repeat: no-repeat;
background-size: cover;
filter: blur(4px);
inset: -8px;
position: absolute;
}
`;
this.shadowRoot.appendChild(style);
};
get description () {
return this.getAttribute('description');
}
set description (value) {
if (value) {
this.setAttribute('description', value);
} else {
this.removeAttribute('description');
}
}
get headingtag () {
return this.getAttribute('headingtag');
}
set headingtag (value) {
if (value) {
this.setAttribute('headingtag', value);
} else {
this.removeAttribute('headingtag');
}
}
get slug () {
return this.getAttribute('slug');
}
set slug (value) {
if (value) {
this.setAttribute('slug', value);
} else {
this.removeAttribute('slug');
}
}
get image () {
return this.getAttribute('image');
}
set image (value) {
if (value) {
this.setAttribute('image', value);
} else {
this.removeAttribute('image');
}
}
get user () {
return this.getAttribute('user');
}
set user (value) {
if (value) {
this.setAttribute('user', value);
} else {
this.removeAttribute('user');
}
}
}
// Define the new web component
if ('customElements' in window) {
customElements.define('code-pen', codePenHTML);
}
Also see: Tab Triggers