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 URL's 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 it's URL and the proper URL extention.
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.
<div id="app">
<h1>Starting at Hogwarts</h1>
<p><em>You don't have any todo items yet.</em></p>
</div>
var support = (function () {
if (!window.DOMParser) return false;
var parser = new DOMParser();
try {
parser.parseFromString('x', 'text/html');
} catch(err) {
return false;
}
return true;
})();
/**
* Convert a template string into HTML DOM nodes
* @param {String} str The template string
* @return {Node} The template HTML
*/
var stringToHTML = function (str) {
// If DOMParser is supported, use it
if (support) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
}
// Otherwise, fallback to old-school method
var dom = document.createElement('div');
dom.innerHTML = str;
return dom;
};
/**
* Create an array of the attributes on an element
* @param {NamedNodeMap} attributes The attributes on an element
* @return {Array} The attributes on an element as an array of key/value pairs
*/
var getAttributes = function (attributes) {
return Array.prototype.map.call(attributes, function (attribute) {
return {
att: attribute.name,
value: attribute.value
};
});
};
/**
* Create a DOM Tree Map for an element
* @param {Node} element The element to map
* @param {Boolean} isSVG If true, node is within an SVG
* @return {Array} A DOM tree map
*/
var createDOMMap = function (element, isSVG) {
return Array.prototype.map.call(element.childNodes, (function (node) {
var details = {
content: node.childNodes && node.childNodes.length > 0 ? null : node.textContent,
atts: node.nodeType !== 1 ? [] : getAttributes(node.attributes),
type: node.nodeType === 3 ? 'text' : (node.nodeType === 8 ? 'comment' : node.tagName.toLowerCase()),
node: node
};
details.isSVG = isSVG || details.type === 'svg';
details.children = createDOMMap(node, details.isSVG);
return details;
}));
};
var getStyleMap = function (styles) {
return styles.split(';').reduce(function (arr, style) {
if (style.trim().indexOf(':') > 0) {
var styleArr = style.split(':');
arr.push({
name: styleArr[0] ? styleArr[0].trim() : '',
value: styleArr[1] ? styleArr[1].trim() : ''
});
}
return arr;
}, []);
};
var removeStyles = function (elem, styles) {
styles.forEach(function (style) {
elem.style[style] = '';
});
};
var changeStyles = function (elem, styles) {
styles.forEach(function (style) {
elem.style[style.name] = style.value;
});
};
var diffStyles = function (elem, styles) {
// Get style map
var styleMap = getStyleMap(styles);
// Get styles to remove
var remove = Array.prototype.filter.call(elem.style, function (style) {
var findStyle = styleMap.find(function (newStyle) {
return newStyle.name === style && newStyle.value === elem.style[style];
});
return findStyle === undefined;
});
// Add and remove styles
removeStyles(elem, remove);
changeStyles(elem, styleMap);
};
var removeAttributes = function (elem, atts) {
atts.forEach(function (attribute) {
// If the attribute is a class, use className
// Else if it's style, remove all styles
// Otherwise, use removeAttribute()
if (attribute.att === 'class') {
elem.className = '';
} else if (attribute.att === 'style') {
removeStyles(elem, Array.prototype.slice.call(elem.style));
} else {
elem.removeAttribute(attribute.att);
}
});
};
/**
* Add attributes to an element
* @param {Node} elem The element
* @param {Array} atts The attributes to add
*/
var addAttributes = function (elem, atts) {
atts.forEach(function (attribute) {
// If the attribute is a class, use className
// Else if it's style, diff and update styles
// Otherwise, set the attribute
if (attribute.att === 'class') {
elem.className = attribute.value;
} else if (attribute.att === 'style') {
diffStyles(elem, attribute.value);
} else {
elem.setAttribute(attribute.att, attribute.value || true);
}
});
};
/**
* Diff the attributes on an existing element versus the template
* @param {Object} template The new template
* @param {Object} existing The existing DOM node
*/
var diffAtts = function (template, existing) {
// Get attributes to remove
var remove = existing.atts.filter(function (att) {
var getAtt = template.atts.find(function (newAtt) {
return att.att === newAtt.att;
});
return getAtt === undefined;
});
// Get attributes to change
var change = template.atts.filter(function (att) {
var getAtt = find(existing.atts, function (existingAtt) {
return att.att === existingAtt.att;
});
return getAtt === undefined || getAtt.value !== att.value;
});
// Add/remove any required attributes
addAttributes(existing.node, change);
removeAttributes(existing.node, remove);
};
/**
* Make an HTML element
* @param {Object} elem The element details
* @return {Node} The HTML element
*/
var makeElem = function (elem) {
// Create the element
var node;
if (elem.type === 'text') {
node = document.createTextNode(elem.content);
} else if (elem.type === 'comment') {
node = document.createComment(elem.content);
} else if (elem.isSVG) {
node = document.createElementNS('http://www.w3.org/2000/svg', elem.type);
} else {
node = document.createElement(elem.type);
}
// Add attributes
addAttributes(node, elem.atts);
// If the element has child nodes, create them
// Otherwise, add textContent
if (elem.children.length > 0) {
elem.children.forEach(function (childElem) {
node.appendChild(makeElem(childElem));
});
} else if (elem.type !== 'text') {
node.textContent = elem.content;
}
return node;
};
/**
* Diff the existing DOM node versus the template
* @param {Array} templateMap A DOM tree map of the template content
* @param {Array} domMap A DOM tree map of the existing DOM node
* @param {Node} elem The element to render content into
*/
var diff = function (templateMap, domMap, elem) {
// If extra elements in domMap, remove them
var count = domMap.length - templateMap.length;
if (count > 0) {
for (; count > 0; count--) {
domMap[domMap.length - count].node.parentNode.removeChild(domMap[domMap.length - count].node);
}
}
// Diff each item in the templateMap
templateMap.forEach(function (node, index) {
// If element doesn't exist, create it
if (!domMap[index]) {
elem.appendChild(makeElem(templateMap[index]));
return;
}
// If element is not the same type, replace it with new element
if (templateMap[index].type !== domMap[index].type) {
domMap[index].node.parentNode.replaceChild(makeElem(templateMap[index]), domMap[index].node);
return;
}
// If attributes are different, update them
diffAtts(templateMap[index], domMap[index]);
// If content is different, update it
if (templateMap[index].content !== domMap[index].content) {
domMap[index].node.textContent = templateMap[index].content;
}
// If target element should be empty, wipe it
if (domMap[index].children.length > 0 && node.children.length < 1) {
domMap[index].node.innerHTML = '';
return;
}
// If element is empty and shouldn't be, build it up
// This uses a document fragment to minimize reflows
if (domMap[index].children.length < 1 && node.children.length > 0) {
var fragment = document.createDocumentFragment();
diff(node.children, domMap[index].children, fragment);
elem.appendChild(fragment);
return;
}
// If there are existing child elements that need to be modified, diff them
if (node.children.length > 0) {
diff(node.children, domMap[index].children, domMap[index].node);
}
});
};
// The new UI
var template = `
<div id="app">
<h1>Starting at Hogwarts</h1>
<ul>
<li>
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 800 800">
<title>Completed</title>
<path d="M0 0v800h800V0H0zm750 750H50V50h700v700z"/>
</svg>
Fix my wand
</li>
<li>
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 800 800">
<title>Incomplete</title>
<path d="M0 0v800h800V0H0zm750 750H50V50h700v700z"/>
<path d="M125 400l75-75 125 125 275-275 75 75-350 350z"/>
</svg>
Buy new robes
</li>
<li>
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 800 800">
<title>Incomplete</title>
<path d="M0 0v800h800V0H0zm750 750H50V50h700v700z"/>
<path d="M125 400l75-75 125 125 275-275 75 75-350 350z"/>
</svg>
Enroll in courses
</li>
</ul>
</div>`;
// Get the existing UI node
var app = document.querySelector('#app');
// Get DOM maps
var templateMap = createDOMMap(stringToHTML(template));
var domMap = createDOMMap(app);
// Diff the DOM
diff(templateMap, domMap, app);
Also see: Tab Triggers