JavaScript

This is an introduction to the JavaScript functionality provided by Stacks.

Including the Stacks JavaScript

While Stacks is first and foremost a CSS library, it also provides commonly used functionality for some components via JavaScript. This functionality is optional. If you only need the styling parts of Stack, you’re free to ignore the provided JavaScript. The converse is not true: The JavaScript components work under the assumption that the Stacks CSS is available.

Stacks JavaScript is currently included within various Stack Overflow projects automatically. If you’re working on a Stack Overflow project, chances are it’s already available for you! If not, reach out to us and we’ll work on getting it setup.

To include Stacks JavaScript in other projects, do the following.

  • Include the file dist/js/stacks.min.js in your page. For example, if you use the unpkg CDN, add the tag <script src="https://unpkg.com/@stackoverflow/stacks/dist/js/stacks.min.js"></script> to your HTML. See Using Stacks for more information on Unpkg and installing Stacks via NPM.
  • If you need to support Internet Explorer 11, you also have to include a polyfill dist/js/stacks.polyfills.min.js. This file has to be included before the main JavaScript file.

Using the Stacks JavaScript

The Stacks JavaScript components are provided as Stimulus controllers. Stimulus is a library created by Basecamp (formerly 37Signals).

Stimulus allows you to add functionality to your markup in a way that is similar to how you add styling to your markup: by modifying HTML attributes.

Just as you style components by adding classes to the class attribute, with Stacks JavaScript, you’ll give components optional functionality by adding data-… attributes to the HTML.

The basic functional unit of Stimulus, and of a Stacks JavaScript component, is a controller. Controllers are identified by their name, and all Stacks-provided controller names are prefixed with s-…, just like component CSS classes. You give functionality to an HTML element by setting its data-controller attribute.

1
<div class="s-magic-widget s-magic-widget__awesome" data-controller="s-magic-widget"></div>

Refer to the documentation of individual components on how to configure a component’s behavior.