Alert & Button Plugins

Two small, single-purpose plugins in one lesson. The Alert plugin is what makes the close button on an alert actually dismiss it. The Button plugin adds a loading state and toggle behavior to plain .btn elements. Both are tiny, but both power interactions you'll want in almost every TrailMap page.

Alert Plugin: data-dismiss="alert"

Add data-dismiss="alert" to a close button inside an .alert, and clicking it fades the alert out (via transition.js) and removes it from the DOM entirely — no JavaScript of your own required. This is exactly what makes the close button from the earlier Alerts lesson work.

<!-- TrailMap: dismissible alert -->
<div class="alert alert-warning fade in">
  <button type="button" class="close" data-dismiss="alert">&times;</button>
  Trail closed for maintenance until further notice.
</div>

The jQuery equivalent, if you need to close an alert from your own code: $('.alert').alert('close').

Button Plugin: Loading State

Add data-loading-text to a button, then call .button('loading') to swap in that text while an async action runs. Call .button('reset') to restore the original label afterward.

<!-- TrailMap: "Save Trail" button -->
<button id="saveTrailBtn" type="button" class="btn btn-primary"
        data-loading-text="Saving...">Save Trail</button>

<script>
$('#saveTrailBtn').on('click', function() {
  var $btn = $(this);
  $btn.button('loading'); // button now reads "Saving..." and is disabled

  $.post('/api/save-trail', { id: 42 }, function() {
    $btn.button('reset'); // back to "Save Trail"
  });
});
</script>

Button Plugin: Single Toggle vs. Toggle Groups

A lone button can act like a checkbox with data-toggle="button" — clicking it flips .active on and off:

<button type="button" class="btn btn-default" data-toggle="button">Favorite</button>

For a whole group of checkbox- or radio-style toggle buttons, wrap them in .btn-group with data-toggle="buttons" (plural) on the wrapper, and put real <input type="checkbox"> or <input type="radio"> elements inside each label:

<!-- TrailMap: filter trails by terrain (multi-select) -->
<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-default">
    <input type="checkbox"> Forest
  </label>
  <label class="btn btn-default">
    <input type="checkbox"> Ridge
  </label>
</div>
button vs. buttons: data-toggle="button" (singular) is for one standalone toggleable button; data-toggle="buttons" (plural) is for the group wrapper around several radio/checkbox inputs styled as buttons. Easy to mix up, easy to remember once you notice the "s".
Up next: Collapse — expandable sections and accordions, plus a real Bootstrap-3-vs-4 naming difference worth knowing.