Stack Snippets are an on-site tool similar to jsfiddle.net, codepen.io or plnkr.co. They're more limited than those tools, but they have the advantage of being on-site, so your code/markup is in your question (or answer), not just linked, and so it's accessible even if the off-site location isn't, and people don't have to go off-site to help you / get help from you.
They were announced and initially documented in this SE blog post, but it's markedly out of date now.
In a snippet, you provide your HTML and/or CSS and/or JavaScript, and then it can be run with a click of a button, with the result shown in your post.
Note: Snippets are for runnable examples in the browser demonstrating a problem. If your snippet code isn't going to be runnable in the browser (see Steps 3 and 4 below), don't use a snippet; just highlight it and use the {}
button (or Ctrl+K) — or indent each line with four spaces — to format as a code block instead.
This answer covers snippets generically. Some libraries or technologies have their own answers tailored specifically to them:
Basics
You can add a Stack Snippet either by using the built-in editor GUI or by adding the <!-- begin snippet -->
(with optional options) and <!-- end snippet -->
comments manually, with HTML and/or CSS and/or JavaScript sections between them.
Editor GUI
To create a snippet:
Open the Stack Snippets editor, either by clicking the toolbar button or, with the cursor in the answer box, by pressing Ctrl+M:
That will give you a pop-up dialog with controls on the left and four panes on the right:
Enter your HTML, CSS, and/or JavaScript, putting each (with no wrapper) in its labelled pane. Don't put a <html>...</html>
or <body>...</body>
tag around your html, <script>...</script>
tag around your JavaScript or <style>...</style>
tag around your CSS; that will be done for you. Just put them in the correct pane. (Note that putting non-body
content in the HTML panel will produce invalid HTML in the snippet when run. It may mostly work, but at best it'll be misleading.¹)
If your code needs AJAX, you can simulate it with setTimeout
and static data.
If you need to show that preventDefault
isn't preventing the default of following a link, see this question about how to do that (since Stack Snippets won't let you navigate to a different document or open a new window). (TL;DR - Use a link to a fragment identifier.)
If your code needs localStorage
or sessionStorage
, those aren't supported by Snippets, but you can use a fake version like this one from Heretic Monkey.
When you've put in your HTML, CSS, and/or JavaScript, click the Run button to make sure the snippet shows what you want it to show in the Result pane.
Make sure your code is properly and consistently formatted. (You can use the Tidy button in the editor to have it apply its rules to your code if you like.)
When the snippet works, demonstrating what you're trying to show, and the code is properly and consistently formatted, click Save & insert into post to save it to the text of your post and close the snippet editor. (You can always reopen it later by clicking the edit the above snippet link under the snippet.)
Manually
If you are creating/editing a post from an environment that lacks the editor GUI (for example, when submitting posts via the API or mobile devices), it might be useful to know how to build a snippet manually.
The rules for creating a snippet this way are pretty simple:
- Open with an HTML comment:
<!-- begin snippet: js [...options] -->
- Add up to 3 "sections" representing HTML, CSS, and JavaScript parts of the snippet by prefixing each section with a comment:
<!-- language: lang-<js|css|html> -->
(there is no need for all 3 sections to be present)
- Close with an
<!-- end snippet -->
comment
External libraries are added via <script src="<HTTPS link>">
tag and thus require a <!-- language: lang-html -->
section to be present.
Options of the begin-snippet
are added as space-separated name: value
pairs. The following options are available (circa 2021):
Name |
Required |
Values |
Description |
babel |
no |
Boolean |
Transpiles JavaScript if true |
console |
no |
Boolean |
Disables built-in console if false or missing |
hide |
no |
Boolean |
Collapses the snippet if true |
Details
The Panes
The four panes in the snippet editor are:
HTML - The top-left pane. Only the body
content goes here. When you run the snippet, it will be wrapped in markup including <body>...</body>
tags (regardless of whether it belongs in body
or not).¹
CSS - The top-right pane. Your CSS goes here, as though it were in a stylesheet or a <style>...</style>
element (which is where it will go).
JavaScript - The bottom-left pane. Your JavaScript goes here. When the snippet is rendered, this will be in a <script>..</script>
element at the end of the <body>
, after any HTML you've included.
Result - The bottom-right pane. Your snippet is rendered here.
Actions
To run the snippet, click Run
To pass the code and markup through a "pretty-printer", click Tidy
To completely wipe out the code and settings in the snippet editor, click Reset
To leave the editor without saving the snippet to your post, click Cancel
Including libraries, etc.
If the library you want to use is listed in the dropdowns on the left, just pick it from the dropdown; the editor will insert a <script>
tag (or tags) in the HTML for that library. You can always edit or remove it later.
To include a library or stylesheet that isn't listed, you can use the Add an external library button and provide a URL; the editor will then automatically add either a <script>
or a <link>
tag for it in the HTML pane. Typically you'd source these from a CDN like https://cdnjs.com.
AJAX
If your code needs AJAX, you can simulate it with setTimeout
and static data. Instead of:
fetch("/some/resource")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => {
// ...use data here...
})
.catch(/*...*/);
you'd do:
setTimeout(() => {
// ...use data here...
}, 800);
or if you need a promise:
return new Promise(resolve => setTimeout(resolve, 800, {/*...data here...*/}));
Console
By default, an in-snippet console will be included, so that console.log
and similar statements generate output to the result pane. This involves adding console-specific CSS and markup to your snippet, which in some relatively-rare cases may interfere with what you're trying to show. If you don't intend to use console.log
and such, untick the box. If you do, though, it's very handy to have those results shown in the result pane rather than hidden away in the browser's console.
The console is limited to only the bottom of the result window. If your only output is to the console, you can force that area to fill the window by adding this CSS (sadly, there is no actual option for doing this):
.as-console-wrapper {
max-height: 100% !important;
}
The console also by default limits to 50 entries. You can disable that limit using this JavaScript:
console.config({
maxEntries: Infinity
});
...or, of course, use your own limit by supplying a number other than 50. Here's an example that limits the console to five entries:
console.config({
maxEntries: 5
});
let i = 0;
const handle = setInterval(function() {
++i;
console.log(`Entry #${i}`);
if (i === 10) {
clearInterval(handle);
}
}, 1000);
Watch the console, it's been restricted to 5 entries; once it reaches 5, older ones start dropping off as newer ones are added.
canon, who wrote the snippet console, added some other options years ago, but they don't appear to have been deployed to the SE network, and no UI for the options exists.
Transpiling
By default, your code is run "as is" in the browser. But if you tick the Use BabelJS / ES2015 checkbox, your code will be transpiled using the in-browser version of Babel. This isn't needed much anymore as all major browsers support the vast majority of ES2015+, but you'd use it for a React snippet for example.
Showing / Hiding By Default
By default, when you insert your snippet in a post, it will show the content of the snippet. Often that's exactly what you want: to show your code. But if you're doing a snippet that's just a live example of code blocks you've already written, or demonstrating minor tweaks to a previous snippet, etc., you may not want it to take up that much space. If so, tick the Hide snippet by default checkbox.
Example
Here's an example snippet with HTML, CSS, and JavaScript, loading an external library (jQuery):
$(".container").text("Hello, Stack Snippets!");
.container {
margin: 5px;
padding: 5px;
border: 1px solid #02F;
color: #02F;
}
<div class="container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Notice that:
- Our JavaScript is added to the resulting page after the markup in our HTML pane (if it weren't, the snippet above wouldn't show anything because the
<div>
wouldn't be there when the code ran).
- We don't have a
<script>
tag around our JavaScript (it's added for us)
- We don't have a
<style>
tag around our CSS
- In this case, we didn't tick the Hide snippet by default checkbox, so the snippet's code is shown
- Since we weren't using the console, we unticked the Show console checkbox
Here's that exact same snippet, but with the Hide snippet by default checkbox ticked:
$(".container").text("Hello, Stack Snippets!");
.container {
margin: 5px;
padding: 5px;
border: 1px solid #02F;
color: #02F;
}
<div class="container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And here's a JavaScript-only snippet using console.log
:
console.log("Hello, Stack Snippets!");
¹ About putting non-body
content in the HTML pane: Beware that Stack Snippets literally just take when you put there and dump it out in their generated body
tag. So for example, suppose your HTML panel content were this:
<head>
<title>My Title</title>
</head>
<body class="x" onload="console.log('hi there')">
<p>My Paragraph</p>
</body>
What actually gets done by Stack Snippets at runtime is this invalid HTML:
<!DOCTYPE html>
<html>
<head><!-- generated snippet head --></head>
<body><head>
<title>My Title</title>
</head>
<body class="x" onload="console.log('hi there')">
<p>My Paragraph</p>
</body>
<script>/* code from script pane here */</script>
<!-- optional console snippet div here -->
</body>
</html>
What the browser does with that is largely up to the browser, although the specification has some rules for handling invalid HTML. The result you get in Chromium browsers and Firefox as of this writing is:
<!DOCTYPE html>
<html>
<head><!-- generated snippet head --></head>
<body class="x" onload="console.log('hi')">
<title>Something</title>
<p>My Paragraph</p>
<script>/* code from script pane here */</script>
<!-- optional console snippet div here -->
</body>
</html>
It's nice to see them putting the attributes of the invalid nested body
on the main body
, but as far as I can tell that's not specified behavior. Note that the head
elements were not put in head
, and most head
elements are meaningless when they are dumped out to body
instead.
So again, including only the contents of a body
tag to avoid invalid and potentially misleading content in the Stack Snippet at runtime.