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.
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.1.4/web-animations-next.min.js"></script>
<div id="showcase">
<div class="left">
<header>More</header>
<p>
Photo Showcase searches Picasa for the best pictures this side of the Milky Way.
</p>
<p>
Drag up and down on each photo to show how much you enjoy each one!
Check the console for the logged vote output.
</p>
<p>
Use the drag control below to configure the size of the photos.
</p>
<div class="settings">
<div class="setting" id="setting-size">
<span class="caption">Photo Size</span>
<span class="opt">
<span class="line"></span>
<span class="dot"></span>
</span>
</div>
</div>
</div>
<div class="right">
<header>
⇠
</header>
</div>
<div class="main">
<header>Photo Showcase</header>
<div class="info">
<span class="applogo">
<img class="logopic" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/208665/image-logo.jpeg" />
<img class="logopic blur" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/208665/image-logo.jpeg" />
</span>
<h5>
Photos ⇢
</h5>
<h6>
⇠ Information
</h6>
</div>
</div>
</div>
<div class="scroller">
<div id="photos">
</div>
</div>
/** vars and helper classes */
@color-slider: #5677fc;
.text-highlight {
text-shadow: 0 1px 0 rgba(33, 33, 33, 0.25);
}
.text-highlight-light {
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
}
.shadow-fuzz {
box-shadow: 0 0 6px 1px #777;
}
.active-slider {
transition: background 0.125s;
&:active {
background: fadeout(@color-slider, 90%);
}
}
.position-fill {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.disable-events {
user-select: none;
user-drag: none;
}
.blur {
filter: blur(5px);
}
/** default styles */
* {
margin: 0;
padding: 0;
font: inherit;
}
body {
margin: 0;
min-height: 100%;
font-family: "Roboto", Arial, Sans-Serif;
font-size: 13px;
font-weight: 300;
height: 100%;
background: #eee;
// Never allow the browser to scroll left/right.
overflow: hidden;
}
html {
height: 100%;
position: relative;
overflow: hidden;
}
p {
text-align: left;
margin: 8px 12px;
.text-highlight-light;
}
h5, h6 {
margin: 24px 0;
font-family: "Lobster";
font-size: 32px;
.text-highlight-light;
}
h6 {
font-size: 20px;
}
/** generic header */
header {
height: 48px;
line-height: 48px;
font-size: 20px;
color: white;
font-weight: 400;
text-align: left;
padding: 0 24px;
.text-highlight;
border-bottom: 2px solid rgba(33, 33, 33, 0.25);
}
/** showcase sidebar */
#showcase {
height: 100%;
width: 280px;
left: 0;
top: 0;
position: absolute;
z-index: 100;
header {
cursor: pointer;
}
.disable-events;
}
@media screen and (max-width: 400px) {
#showcase {
width: 100%;
}
}
#showcase .main {
position: relative;
z-index: 9;
background: #fafafa;
height: 100%;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.26);
header {
background: #5264ae;
}
}
#showcase .left {
position: absolute;
z-index: 10;
left: -100%;
width: 100%;
height: 100%;
background: #eee;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.26);
header {
background: #c36b5c;
}
.settings {
border-top: 1px solid rgba(33, 33, 33, 0.125);
}
}
/** right: exists only as 'grabber' to drag us back */
#showcase .right {
position: absolute;
z-index: 8;
right: 0;
width: 48px;
height: 100%; // so it can be grabbed
opacity: 0.75;
header {
background: #52ae7a;
padding: 0;
text-align: center;
font-size: 32px;
}
}
.info {
text-align: center;
margin: 24px 0;
}
/** fancy logo thing */
.applogo {
border-radius: 200px;
width: 120px;
height: 120px;
box-sizing: border-box;
border: 2px solid white;
display: inline-block;
.shadow-fuzz;
.text-highlight;
line-height: 36px;
font-size: 20px;
color: white;
overflow: hidden;
position: relative;
.logopic {
-webkit-mask-image: -webkit-radial-gradient(circle, white, black);
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
border-radius: 1000px;
}
}
/** settings display */
.settings {
text-align: left;
line-height: 34px;
font-weight: 400;
display: block;
.text-highlight-light;
.setting {
display: block;
position: relative;
.active-slider;
.caption {
display: inline-block;
padding: 0 8px;
width: 160px;
text-align: right;
box-sizing: border-box;
float: left;
}
.opt {
will-change: transform;
display: block;
position: relative;
margin-left: 180px;
margin-right: 20px;
cursor: pointer;
@dot-dimen: 12px;
.dot {
will-change: transform;
position: absolute;
width: @dot-dimen;
height: @dot-dimen;
background: #aaa;
border-radius: 100px;
left: 0%;
top: 50%;
margin-top: (-@dot-dimen / 2);
margin-left: (-@dot-dimen / 2);
}
.line {
position: absolute;
background: #aaa;
border-color: inherit;
width: 100%;
left: 0%;
top: 50%;
height: 2px;
margin-top: -1px;
}
// hack to force .opt to always take a line
&::after {
content: ".";
visibility: hidden;
}
}
}
}
/** main photos display */
.scroller {
overflow: scroll;
overflow-y: hidden;
width: 100%;
height: 100%;
position: relative;
}
#photos {
display: flex;
flex-flow: row nowrap;
align-items: center;
width: auto;
height: 100%;
.holder {
display: inline-block;
transition: min-width 0.5s, width 0.5s, height 0.5s;
height: 128px;
min-width: 128px;
margin: 8px;
border: 2px solid white;
.shadow-fuzz;
border-radius: 2px;
background: #ccc;
overflow: hidden;
position: relative;
cursor: pointer;
}
.photo {
.position-fill;
background-size: cover;
background-position: center;
}
.arrow {
position: absolute;
left: 60%;
top: 50%;
margin-left: -32px;
width: 32px;
margin-top: -12px;
height: 32px;
width: 32px;
&::before {
content: "";
position: absolute;
left: 16px;
top: 0;
width: 32px;
height: 32px;
transform: rotate(45deg);
background: inherit;
}
}
}
#photos.size-mid {
.holder {
min-width: 192px;
height: 192px;
}
}
#photos.size-large {
.holder {
min-width: 256px;
height: 256px;
}
}
if (typeof Math.sign != 'function') {
// polyfill for old browsers
Math.sign = function(x) {
x = +x;
if (x === 0 || isNaN(x)) { return x; };
return x > 0 ? 1 : -1;
};
}
/**
* Selector is a controller for scrubbing a single Web Animation. It allows for
* gesture-like semantics insofar as dragging and 'snapping' back to known
* points along a timeline.
*
* @constructor
* @param {Map!} anims map of elements to their steps
* @param {AnimationTiming!} timing as per element.animate
*/
var Selector = function(anims, timing, opt_startAt) {
this.points_ = [];
this.callback = function() {};
// Upgrade AnimationTiming to a real object, if applicable.
if (typeof timing == 'number') { timing = {'duration': timing}; }
this.timing_ = timing;
// The active drift to a valid setpoint, if any.
this.activeDrift_ = null;
this.emptyElement_ = document.createElement('div');
// Build a combined GroupScrubPlayer, for user gestures.
this.anims_ = anims;
this.player_ = new GroupScrubPlayer(this.animateAll_(timing), opt_startAt);
return this;
};
Selector.prototype = {
get points() {
return this.points_.slice();
},
set points(v) {
this.points_ = v.slice();
}
};
/**
* Animates all the managed animations with the specified timing object.
*
* @private
* @param {AnimationTiming!} timing to use
*/
Selector.prototype.animateAll_ = function(timing) {
var players = [];
this.anims_.forEach(function(steps, element) {
var player = element.animate(steps, timing);
players.push(player);
});
return players;
};
/**
* Stops any pending animation on this Selector.
*/
Selector.prototype.stop = function() {
if (this.activeDrift_) {
this.player_.currentTime = this.activeDrift_();
this.activeDrift_ = null;
}
};
/**
* Releases this Selector, kicking off a drift towards the nearest setpoint.
*/
Selector.prototype.release = function() {
if (!this.points_.length) {
return false; // can't release anywhere
}
var currentTime = this.player_.currentTime;
var target = this.points_[0];
// NOTE: Binary search is hard.
for (var i = 1; i < this.points_.length; ++i) {
var first = this.points_[i-1];
var second = this.points_[i];
if (currentTime <= (first + second) / 2) {
target = first;
break;
}
target = second;
}
this.animateTo(target);
};
/**
* Drift along the normal animation's timeline to the given target time.
*
* @param {number} dstTime to animate to
*/
Selector.prototype.animateTo = function(dstTime) {
this.stop();
var duration = this.timing_.duration;
var srcTime = this.player_.currentTime;
var driftDuration = dstTime - srcTime;
// If there's no duration, just callback immediately. This is important as
// otherwise the animation below will never complete: the playbackRate will
// be zero (the sign of driftDuration).
if (!driftDuration) {
this.callback(dstTime);
return;
}
// Set the underlying player's real time erly.
this.player_.currentTime = dstTime;
// Create timing that uses iterationStart and iterations to define a range
// to animate between: e.g. from 0.342 to 0.5. The playbackRate controls
// which direction to animate along this range.
var driftTiming = {
duration: duration,
easing: this.timing_.easing || 'linear',
iterationStart: Math.min(srcTime, dstTime) / duration,
iterations: Math.abs(driftDuration) / duration,
fill: 'none',
playbackRate: Math.sign(driftDuration)
};
// NOTE: Works around a 'flash' when animating from the end of an Animation.
// As we're not filling forwards/backwards, this animation won't do anything
// at 1.0: so don't even try.
if (srcTime == duration) {
driftTiming.iterations -= 0.0001;
}
var driftPlayers = this.animateAll_(driftTiming);
var controlDriftPlayer = this.emptyElement_.animate([], driftTiming);
// Create a callback which cancels the current drift, and returns the
// intermediary position from controlDriftPlayer (which otherwise does
// nothing).
this.activeDrift_ = function() {
var progress = controlDriftPlayer.currentTime * Math.sign(driftDuration);
driftPlayers.forEach(function(player) {
player.cancel();
});
controlDriftPlayer.onfinish = null;
controlDriftPlayer.cancel();
return srcTime + progress;
};
// If the controlDriftPlayer actually finishes, then invoke the callback.
controlDriftPlayer.onfinish = function() {
this.activeDrift_ = null;
this.callback(dstTime);
}.bind(this);
};
/**
* Builds handler for several different approaches to manipulating this
* Selector.
*
* @param {Object!} approach to handling delta
* @param {bool=} opt_stopPropagation whether to stop propogation of this event
*/
Selector.prototype.buildHandler = function(approach, opt_stopPropagation) {
var selector = this;
return function(startEv) {
var startAt = selector.player_.currentTime;
var update = function(begin, end) {
var offsetX = end.screenX - begin.screenX;
var delta;
if (typeof approach == 'number') {
// The approach is a number: just assume we're scrubbing left/right.
delta = offsetX / approach;
} else if (approach.offsetWidth) {
// As above, but pretend that this is the size of a HTML element.
delta = offsetX / approach.offsetWidth;
} else {
// Otherwise, call the function with a 'delta' object.
delta = approach({ x: offsetX, y: end.screenY - begin.screenY });
}
// Set the currentTime, but clamp to [0,duration].
var time = startAt + delta;
time = Math.max(0, Math.min(selector.timing_.duration, time));
selector.player_.currentTime = time;
};
switch (startEv.type) {
case 'mousedown':
var mover = function(ev) {
opt_stopPropagation && ev.stopPropagation();
if (!ev.which || ev.type == 'mouseup') {
document.removeEventListener('mousemove', mover);
document.removeEventListener('mouseup', mover);
return selector.release();
}
update(startEv, ev);
};
document.addEventListener('mousemove', mover);
document.addEventListener('mouseup', mover);
break;
case 'touchstart':
if (!startEv.touches.length) {
return false; // give up early
}
// clone startTouch because of Mobile Safari reusing them.
var t = startEv.touches[0];
var startTouch = {screenX: t.screenX, screenY: t.screenY};
var mover = function(ev) {
opt_stopPropagation && ev.stopPropagation();
if (ev.type == 'touchend') {
document.removeEventListener('touchmove', mover);
document.removeEventListener('touchend', mover);
return selector.release();
}
update(startTouch, ev.changedTouches[0]);
};
document.addEventListener('touchmove', mover);
document.addEventListener('touchend', mover);
break;
default:
throw Error('unsupported handler: ' + startEv.type);
}
selector.stop();
opt_stopPropagation && startEv.stopPropagation();
};
};
/**
* Wraps a number of other AnimationPlayer objects, allowing them to be
* scrubbed as one. Provides currentTime property.
*
* @constructor
* @param {!Array<!AnimationPlayer>} players to wrap
* @param {number=} opt_startAt to start the players at, default zero
*/
var GroupScrubPlayer = function(players, opt_startAt) {
this.players_ = players.slice();
players.forEach(function(player) {
player.pause();
})
// nb: intentionally uses property
this.currentTime = +opt_startAt || 0;
};
GroupScrubPlayer.prototype = {
set currentTime(v) {
this.currentTime_ = v;
this.players_.forEach(function(player) {
player.currentTime = v;
});
},
get currentTime() {
return this.currentTime_;
}
};
/////////////////////
window.photor = {};
window.addEventListener('load', function() {
/**
* Unblur the flower logo when tapped. Just plays a known animation, so that
* the flower returns to being blurred when done.
*/
(function() {
var logo = document.querySelector('.logopic.blur');
var steps = [
{ 'opacity': '0.9' },
{ 'opacity': '0.0', offset: 0.25 },
{ 'opacity': '0.0', offset: 0.75 },
{ 'opacity': '0.9' },
];
var player = logo.animate(steps, {
duration: 2500,
easing: 'ease-in-out',
fill: 'both'
});
player.pause();
logo.addEventListener('click', function() {
if (player.playState == 'running') {
// do nothing, already playing
} else {
player.play();
}
});
}());
/**
* Allow dragging of the sidebar. Merge three unified animations to be
* managed by the same Selector.
*/
(function() {
var showcase = document.getElementById('showcase');
var timing = {
duration: 2500,
fill: 'both',
easing: 'ease-in-out'
};
var stepsMain = [
{ transform: 'translate(-100%, 0)' },
{ transform: 'translate(0, 0)' },
{ transform: 'translate(+50%, 0)' },
];
var left = showcase.querySelector('.left');
var stepsLeft = [
{ transform: 'translate(0, 0)', opacity: 0 },
{ transform: 'translate(0, 0)', opacity: 0, offset: 0.5 },
{ transform: 'translate(+10%, 0)', opacity: 1, offset: 0.55 },
{ transform: 'translate(+50%, 0)', opacity: 1 },
];
var right = showcase.querySelector('.right');
var stepsRight = [
{ transform: 'translate(+100%, 0)', easing: 'ease-in' },
{ transform: 'translate(0, 0)' },
{ transform: 'translate(0, 0)' },
];
var anims = new Map();
anims.set(showcase, stepsMain);
anims.set(left, stepsLeft);
anims.set(right, stepsRight);
var selector = new Selector(anims, timing, 1250);
selector.points = [0, 1250, 2500];
var handler = selector.buildHandler(0.1);
showcase.addEventListener('mousedown', handler);
showcase.addEventListener('touchstart', handler);
}());
/**
* Adds a settings slider for size.
*/
(function() {
var setting = document.getElementById('setting-size');
var timing = { duration: 800, fill: 'both' };
var stepsLine = [
{ background: '#aaa' },
{ background: '#5677fc' },
];
var stepsDot = [
{ left: '0%', background: '#aaa' },
{ left: '100%', background: '#5677fc' },
];
var anims = new Map();
anims.set(setting.querySelector('.line'), stepsLine);
anims.set(setting.querySelector('.dot'), stepsDot);
var selector = new Selector(anims, timing);
selector.points = [0, 400, 800];
selector.callback = function(value) {
photos.classList.toggle('size-mid', value == 400);
photos.classList.toggle('size-large', value == 800);
};
var handler = selector.buildHandler(0.1, true /* stop propogation */);
setting.addEventListener('mousedown', handler);
setting.addEventListener('touchstart', handler);
}());
/**
* Loads and shows photos that can be voted up or down.
*/
var addPicture = (function() {
var arrowSteps = [
{ 'transform': 'rotate(-99deg)', 'background': 'rgb(237, 88, 53)', opacity: 1 },
{ 'transform': 'rotate(0)', 'background': 'rgb(33, 33, 33)', opacity: 0.5 },
{ 'transform': 'rotate(+99deg)', 'background': 'rgb(45, 137, 200)', opacity: 1 },
];
var timing = {
duration: 1000,
easing: 'linear',
fill: 'both'
};
var handlerFn = function(delta) {
return delta.y * 4; // respond to y-delta for the arrow
};
var photos = document.getElementById('photos');
// Can be passed with a URL to display, plus a function to callback for +ve
// or -ve votes.
return function(url, voter) {
var holder = document.createElement('div');
holder.className = 'holder';
photos.insertBefore(holder, photos.firstChild);
var photo = document.createElement('div');
photo.className = 'photo';
photo.style.backgroundImage = 'url(' + url + ')';
holder.appendChild(photo);
var arrow = document.createElement('div');
arrow.className = 'arrow';
holder.appendChild(arrow);
var anims = new Map();
anims.set(arrow, arrowSteps);
var s = new Selector(anims, timing, 500);
s.points = [50, 500, 950];
// Configure a callback: if the arrow ends up at >500, this is -ve;
// if it is <500, this is +ve.
s.callback = function(value) {
if (value > 500) {
voter(-1);
} else if (value < 500) {
voter(+1);
} else {
voter(0);
}
};
var handler = s.buildHandler(handlerFn);
holder.addEventListener('mousedown', handler);
holder.addEventListener('touchstart', handler);
};
loadPhotos('cute cats', 20).then(function(result) {
result = result.map(function(url) {
return url + '?sz=512'; // TODO: 256 for non-retina
});
result.forEach(addPhoto);
}).catch(function(err) {
console.warn('couldn\'t addPhoto', err);
});
}());
/**
* Exposed API to load pictures of a certain term.
*/
window.photor.load = (function() {
var baseURL = 'https://picasaweb.google.com/data/feed/api/all?alt=json&';
var retrievePhotosByTerm = function(term, opt_count) {
opt_count = +opt_count || 10;
return new Promise(function(resolve, reject) {
var url = baseURL + 'q=' + term + '&max-results=' + opt_count;
var x = new XMLHttpRequest()
x.open('GET', url);
x.responseType = 'json';
x.onload = function() {
resolve(x.response.feed.entry);
};
x.onerror = function() {
reject(x.response);
};
x.send();
});
};
var seen = {};
return function(term, voter, opt_count) {
var p = retrievePhotosByTerm(term, opt_count);
p.then(function(pictures) {
// Don't add the same picture more than once.
pictures = pictures.filter(function(raw) {
var id = raw.id.$t;
if (id in seen) {
return false;
}
seen[id] = true;
return true;
});
// Add brand new pictures!
pictures.forEach(function(raw) {
var url = raw.content.src + '?sz=512';
addPicture(url, voter.bind(null, raw));
});
}, function(err) {
console.warn('couldn\'t add pictures', err);
})
};
}());
});
Also see: Tab Triggers