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.
mixin code
code
p var options = {
p   interval: 2500,
p   transition: {
p     time: 500,
p     curve: 'ease-out',
p   },
p   effects: {
p     fade: true,
p     direction: 'top',
p   }
p }
p  
p new Slideshow(document.querySelector('.slideshow'), options);
.container
h1 Slideshow component
.slideshow
each size in ['500x400', '400x300', '200x600', '300x300', '500x200', '200x400', '500x300', '600x300', '300x400']
img(src="https://source.unsplash.com/random/" + size)
p One line implementation customizable with options
+code
body {
margin: 0;
padding: 20px;
height: 100%;
font-family: sans-serif;
background-color: #fafafa;
}
.container {
max-width: 600px;
margin: auto;
}
h1 {
text-align: center;
margin: 0 0 20px 0;
}
p {
font-size: 14px;
}
code {
background-color: rgba(slategray, 0.2);
border: 1px solid slategray;
border-radius: 6px;
padding: 6px 10px;
font-size: 12px;
display: block;
margin-bottom: 20px;
p {
margin: 0;
padding: 0;
font-size: inherit;
}
}
.slideshow {
margin: auto;
height: 300px;
width: 400px;
}
/*
A portable, customizable slideshow
component for web, built as a JS class
with configurable options and argument
validation, and easily implemented
with a single line of code. No
additional dependencies required.
*/
class Slideshow {
constructor(node, options = {}){
if (!node || !(node instanceof HTMLElement)){
throw new Error('ArgumentError: Constructor requires argument of type HTMLElement')
}
this._node = node;
this._slides = Array.from(node.querySelectorAll('img'));
this._settings = {
autoStart: true,
interval: 3000,
transition: {
time: 400,
curve: ''
},
effects: {
fade: true,
direction: 'left',
scale: 1,
rotate: 0
},
rotation: [
{visibility:'hidden'},
{visibility:'visible'},
{visibility:'hidden'}
]
}
this._state = {
current: 0, // current slide
intervalInstance: null,
}
this._cycle = this._cycle.bind(this);
this._rotate = this._rotate.bind(this);
this._configure(options);
// auto start
if (this._settings.autoStart){
this.start();
}
}
get node() {
return this._node;
}
get slides() {
return this._slides;
}
get current() {
return this._state.current;
}
get interval() {
return this._settings.interval;
}
get intervalInstance() {
return this._state.intervalInstance;
}
get transition() {
return this._settings.transition;
}
get rotation() {
return this._settings.rotation;
}
get effects() {
return this._settings.effects;
}
_configure(options) {
this._applySettings(options);
this._initialize();
}
_applySettings(options) {
// apply general settings
const strongParams = validate(options);
Object.assign(this._settings, strongParams);
console.log(this._settings)
// apply effects settings
const effects = this.effects;
const rotation = this._settings.rotation;
// fade
if (effects.fade){
rotation[0].opacity = 0;
rotation[1].opacity = 1;
rotation[2].opacity = 0;
}
// direction
switch (effects.direction){
case 'left':
case 'right':
case 'top':
case 'bottom':
rotation[0][effects.direction] = '-100%';
rotation[1][effects.direction] = 0;
rotation[2][effects.direction] = '100%';
break;
default:
}
// HELPER FUNCTIONS
// data validation
function permit(obj, allowed){
const newObj = JSON.parse(JSON.stringify(obj));
for(let key in newObj) {
if (!allowed.includes(key)) delete newObj[key];
}
return newObj;
}
function validate(options){
const root = permit(options, ['autoStart', 'interval', 'transition', 'effects']);
// autoStart
clean(root, 'autoStart', 'boolean', 'options.autoStart');
// interval
clean(root, 'interval', 'number', 'options.interval');
// transition
clean(root, 'transition', 'object', 'options.transition');
if (root.hasOwnProperty('transition')){
root.transition = permit(root.transition, ['time', 'curve']);
const transition = root.transition
clean(transition, 'time', 'number', 'transition.time');
clean(transition, 'curve', 'string', 'transition.curve');
}
// effects
clean(root, 'effects', 'object', 'options.effects');
if (root.hasOwnProperty('effects')){
root.effects = permit(root.effects, ['fade', 'direction']);
const effects = root.effects;
clean(effects, 'fade', 'boolean', 'effects.fade');
clean(effects, 'direction', 'string', 'effects.direction');
if (
effects.hasOwnProperty('direction')
&& !['left', 'right', 'top', 'bottom', 'none'].includes(effects.direction)
) {
delete effects.direction;
}
}
return root;
// helper
function clean(obj, key, type, name){
if (obj.hasOwnProperty(key) && typeof obj[key] != type) {
delete obj[key];
console.error(`${name} must be of type ${type}`);
}
}
}
}
_initialize() {
// change parent node into a pinnable position if not already
if (['', 'static'].includes(this.node.style.position)) {
this.node.style.position = 'relative';
}
this.node.style.overflow = 'hidden';
// set default styles for slides
const oppositeAxis = {
right: 'left',
left: 'right',
top: 'bottom',
bottom: 'top'
};
this.slides.forEach(slide => {
Object.assign(slide.style, {
position: 'absolute',
height: '100%',
width: '100%',
objectFit: 'cover',
transition: `${this.transition.time}ms ${(this.transition.curve || '')}`
});
if (['left', 'right', 'top', 'bottom'].includes(this.effects.direction)){
slide.style[oppositeAxis[this.effects.direction]];
} else {
Object.assign(slide.style, { top: 0, left: 0 });
}
});
// clone images if only two images for smooth transition
if (this.slides.length == 2) {
const slideHTML = this.node.innerHTML;
this.node.innerHTML = slideHTML + slideHTML;
this._slides = Array.from(this.node.querySelectorAll('img'))
}
// set initial rotation position styles
Object.assign(this.slides[0].style, this.rotation[1]);
this.slides.slice(1).forEach(slide => {
Object.assign(slide.style, this.rotation[2]);
});
}
start(){
// initialize rotation interval call
if (this.slides.length > 1) {
this._state.intervalInstance = setInterval(this._rotate, this.interval);
}
}
_cycle(index) {
let last = this.slides.length - 1;
return index < 0 ? last : index > last ? 0 : index;
}
_rotate(next = this._cycle(this.current + 1)) {
this._state.current = next;
for(let i=0; i<3; i++){
Object.assign(
this.slides[this._cycle(this.current + i - 1)].style,
this.rotation[i]
);
}
}
}
var options = {
interval: 2500,
transition: {
time: 500,
},
effects: {
}
}
// script
var options = {
interval: 2500,
transition: {
time: 500,
curve: 'ease-out',
},
effects: {
fade: true,
direction: 'top',
}
}
// one line initiation of a Slideshow component
new Slideshow(document.querySelector('.slideshow'), options);
Also see: Tab Triggers