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-

The code for above snippet is -

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />


<div style="padding:5px 0;">
<select id='myselect' class="js-example-basic-single pb-2" name="state" style="width:100%;">
<option value="AL">Alabama</option>
<option value="AS">Alsbama</option>
<option value="WY">Wyoming</option>
</select>
</div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit,<br/>
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br/>
Ut enim ad minim veniam, quis nostrud exercitation ullamco<br/>
laboris nisi ut aliquip ex ea commodo consequat.<br/>
Duis aute irure dolor in reprehenderit in voluptate velit esse<br/>
cillum dolore eu fugiat nulla pariatur.<br/>
Excepteur sint occaecat cupidatat non proident, sunt <br/>
in culpa qui officia deserunt mollit anim id est laborum.


<script>
$(document).ready(function() {
$('#myselect').select2();
})
</script>
Under the hood

Under the hood, we run snippets in a sandboxed iframe with code loaded from another sister website - https://dilifsnippets.com

  • We use HTML5 sandboxed iframes in order to prevent many forms of malicious attack.
  • We render the Snippets on an external domain (dilifsnippets.com) 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.

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.