Code snippets

When creating documentation, it is highly desirable to show custom runnbable css or javascript. Sites like JSFiddle allow previewing runnable working code but two problems-

  1. If the links break, its a bad experience.
  2. It takes your customers to a different site.

Snippets allow you to embed runnable JavaScript, CSS, and HTML code blocks right in the body of a post.

How Do I Make A Stack Snippet?

To create a snippet, click on the snippet button on the editor toolbar

For snippet code, add the javascript functions or css you want to add. If you want to run complex stuff, write it with proper html/body tags. Save the edit and whenever the page loads, the snippet is run and output displayed. For instance, here is an example of formatting a html select element using select2 javascript plugin-

Under the hood

Under the hood, we run snippets in a sandboxed iframe with code loaded from another sister website -

  • We use HTML5 sandboxed iframes in order to prevent many forms of malicious attack.
  • We render the Snippets on an external domain ( in order to ensure that the same-origin policy is not in effect and to keep the snippets from accessing user's logged-in session or cookies.
  • This also means a lot of ultra high security checks are enforced by browsers and well and certain things won't work. E.g. Javascript code that tries to read localstore or sessionstore won't work.

But still snippets are not fully free from malicious code like infinite loops. Hence we have restricted snippets to documentation which is written by the project owner alone.