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.
<h1>Responsive BehaviourController Demo</h1>
<h2>Clock</h2>
<p>Clock will be active as long as the window is larger than 600 pixels.</p>
<div class="component">
<div data-behaviour="Clock" data-conditions='{"window":{"minWidth":600}}'>Clock is inactive</div>
</div>
<h2>ClearField</h2>
<p>ClearField will be active as long as the window is smaller than 600 pixels.</p>
<div class="component">
<input type="text" data-behaviour="ClearField" data-conditions='{"window":{"maxWidth":600}}'>
</div>
html {
background:#fff;
line-height:1.5;
padding:2em;
color:#999;
overflow:scroll;
}
html,input,textarea,button {
font-family:Helvetica,Verdana,sans-serif;
font-size:1em;
}
h1 {
font-size:1.5em;
color:#333;
}
h2 {
margin-top:1.5em;
font-size:1.25em;
color:#333;
}
h2+p {
margin-top:-.75em;
}
p {
max-width:30em;
}
.component {
padding:1em;
border:1px dotted #ccc;
}
/*
* Bind shim
*/
// bind method
if (Function.prototype.bind == null) {
Function.prototype.bind = (function (slice){
// (C) WebReflection - Mit Style License
function bind(context) {
var self = this; // "trapped" function reference
// only if there is more than an argument
// we are interested into more complex operations
// this will speed up common bind creation
// avoiding useless slices over arguments
if (1 < arguments.length) {
// extra arguments to send by default
var $arguments = slice.call(arguments, 1);
return function () {
return self.apply(
context,
// thanks @kangax for this suggestion
arguments.length ?
// concat arguments with those received
$arguments.concat(slice.call(arguments)) :
// send just arguments, no concat, no slice
$arguments
);
};
}
// optimized callback
return function () {
// speed up when function is called without arguments
return arguments.length ? self.apply(context, arguments) : self.call(context);
};
}
// the named function
return bind;
}(Array.prototype.slice));
}
/*
* Observer
*/
var Observer = {
// subscribe to event
subscribe:function(obj,type,fn) {
if (!obj._listeners) {
obj._listeners = new Array();
}
// check if already added
var test,i,l = obj._listeners;
for (i=0; i<l; i++) {
test = obj._listeners[i];
if (test.type === type && test.fn === fn) {
return;
}
}
// add event
obj._listeners.push({'type':type,'fn':fn});
},
// unsubscribe from event
unsubscribe:function() {
if (!obj._listeners) {
return;
}
// find and remove
var test,i;
for (i = obj._listeners.length-1; i >= 0; i--) {
test = obj._listeners[i];
if (test.type === type && test.fn === fn) {
obj._listeners.splice(i,1);
break;
}
}
},
// fire event
fire:function(obj,type,data) {
if (!obj._listeners) {
obj._listeners = new Array();
}
// find and execute callback
var test,i,l = obj._listeners.length;
for (i=0; i<l; i++) {
test = obj._listeners[i];
if (test.type === type) {
test.fn(data);
}
}
}
};
/*
* BehaviourBase Abstract Class
*/
var BehaviourBase = function(element) {
this._element = element;
this._element.setAttribute('data-initialized', 'true');
};
BehaviourBase.prototype._unload = function() {
this._element.removeAttribute('data-initialized');
};
/*
* Clock Class
*/
var Clock = function(element) {
// Call BehaviourBase constructor
BehaviourBase.call(this,element);
// backup content
this._inner = this._element.innerHTML;
// start ticking
this.tick();
};
// Extend from BehaviourBase
Clock.prototype = Object.create(BehaviourBase.prototype);
// Update time
Clock.prototype.tick = function() {
this._element.textContent = new Date().toString();
var self = this;
this._timer = setTimeout(function(){
self.tick();
},1000);
};
// Unload Clock behaviour
Clock.prototype._unload = function() {
// call BehaviourBase unload method
BehaviourBase.prototype._unload.call(this);
// stop ticking
clearTimeout(this._timer);
// restore content
this._element.innerHTML = this._inner;
};
/*
* ClearField Class
*/
var ClearField = function(element) {
// Call BehaviourBase constructor
BehaviourBase.call(this,element);
// Add clear button
var clearButton = document.createElement('button');
clearButton.textContent = 'clear';
clearButton.addEventListener('click',this);
this._element.parentNode.insertBefore(clearButton,this._element);
};
// Extend from BehaviourBase
ClearField.prototype = Object.create(BehaviourBase.prototype);
// Handle events
ClearField.prototype.handleEvent = function(e) {
if (e.type === 'click') {
this._element.value = '';
}
};
// Unload ClearField behaviour
ClearField.prototype._unload = function() {
// call BehaviourBase unload method
BehaviourBase.prototype._unload.call(this);
// get button reference
var clearButton = this._element.previousSibling;
// remove events
clearButton.removeEventListener('click',this);
// remove clear button
this._element.parentNode.removeChild(clearButton);
};
/*
* BehaviourConditions Class
*/
var BehaviourConditions = function(element,properties) {
// is the conditions are suitable, by default they are
this._suitable = true;
// set properties object
this._properties = properties;
// listen for environment changes
this._listen();
// test the conditions
this._test();
};
// Static method construct creates behaviour condition objects
BehaviourConditions.construct = function(element) {
// check if has specifications
var specifications = element.getAttribute('data-conditions');
if (!specifications) {
return null;
}
var properties = null;
try {
properties = JSON.parse(specifications);
}
catch(e) {
console.warn("BehaviourConditions: data-conditions attribute should have format data-conditions='{\"foo\":\"bar\"}'");
return null;
}
return new BehaviourConditions(element,properties)
};
// Adds listeners to the environment to act when it changes
BehaviourConditions.prototype._listen = function() {
if (this._properties.window) {
window.addEventListener('resize',this);
}
};
// Handles events
BehaviourConditions.prototype.handleEvent = function(e) {
switch(e.type) {
case 'resize':{
this._test();
}
break;
default: {}
break;
}
};
// Checks if the current conditions match the requested properties
BehaviourConditions.prototype._test = function() {
// test condition properties
var win,windowSize,suitable = true;
// test window sizes
if (win = this._properties.window) {
// get window size
windowSize = {x:window.innerWidth,y:window.innerHeight};
// check max width
if (win.maxWidth && windowSize.x > win.maxWidth) {
suitable = false;
}
// check min width
if (win.minWidth && windowSize.x < win.minWidth) {
suitable = false;
}
// check max height
if (win.maxHeight && windowSize.y > win.maxHeight) {
suitable = false;
}
// check max height
if (win.minHeight && windowSize.y < win.minHeight) {
suitable = false;
}
}
// fire changed event if condition suitability changed
if (suitable != this._suitable) {
this._suitable = suitable;
Observer.fire(this,'change');
}
};
// Returns the true if the current conditions are met
BehaviourConditions.prototype.areMet = function() {
return this._suitable;
};
/*
* BehaviourLoader Class
*/
var BehaviourLoader = function(element) {
// set element reference
this._element = element;
// check if environment specified
this._environment = BehaviourConditions.construct(this._element);
if (!this._environment) {
this._loadBehaviour();
}
else {
// listen to changes in environment
Observer.subscribe(this._environment,'change',this._onConditionsChange.bind(this));
// if conditions are suitable, load my behaviour
if (this._environment.areMet()) {
this._loadBehaviour();
}
}
};
// Called when behaviour conditions change.
BehaviourLoader.prototype._onConditionsChange = function(e) {
var suitable = this._environment.areMet();
if (this._behaviour && !suitable) {
this.unloadBehaviour();
}
if (!this._behaviour && suitable) {
this._loadBehaviour();
}
};
// Load the behaviour set in the data-behaviour attribute
BehaviourLoader.prototype._loadBehaviour = function() {
var classPath = this._element.getAttribute('data-behaviour');
this._behaviourConstructor = window[classPath];
this._behaviour = new this._behaviourConstructor(this._element);
};
// Unload the behaviour
BehaviourLoader.prototype.unloadBehaviour = function() {
if (!this._behaviour) {
return false;
}
this._behaviour._unload();
this._behaviour = null;
return true;
};
/*
* BehaviourController Static Class
*/
var BehaviourController = {
applyDefault:function() {
document.addEventListener('DOMContentLoaded',function(){
BehaviourController.applyBehaviour(document);
});
},
// Applies behaviour to given context
applyBehaviour:function(context) {
var behaviourConstructor,nodes,i,l;
nodes = context.querySelectorAll('[data-behaviour]:not([data-processed])');
l = nodes.length;
for (i=0;i<l;i++) {
// mark node as processed
nodes[i].setAttribute('data-processed','true');
// wrap in loader
new BehaviourLoader(nodes[i]);
}
}
};
// Run
BehaviourController.applyDefault();
Also see: Tab Triggers