
Understanding JavaScript plugins
As I said, Bootstrap offers a lot of JavaScript plugins. They all come together when we download the framework, and all of them are ready for use when the bootstrap.js
file is loaded in HTML, although each plugin can be downloaded individually as well from the Bootstrap website.
The library dependencies
While we were setting up our development environment, we spoke about the need to import the jQuery library. Actually, jQuery is now the only required external dependency for Bootstrap.
Check out the bower.json
file in the Bootstrap repository for further information about dependencies.
Data attributes
HTML5 introduced the idea of adding custom attributes to document tags in order to store custom information. Therefore, you can add an attribute to a tag with the data-*
prefix, retrieve the information in JavaScript, and not get started with some plugin in your browser. An overwhelming majority of web browsers do support the use of custom data attributes.
With that ideology, Bootstrap implemented all the plugins to be used with just data attributes. This goes towards the framework idea to increase the speed of development and prototyping. This is because you can make use of plugins without typing JavaScript code.
To control that methodology, Bootstrap implemented an API so that you can access all plugins through only data attributes. Sometimes, however, you may want to turn off access through the API. To do so, insert the following command at the beginning of your JavaScript code:
$(document).off('.data-api');
To disable the API for some specific plugins, prepend the plugin namespace. For instance, to disable the alerts API, type this:
$(document).off('.alert.data-api');
Bootstrap JavaScript events
There is a set of events that Bootstrap produces for each plugin. They are triggered usually before and after the event starts. To exemplify this, let's say that we have a Bootstrap modal (you will learn about using modals in this chapter; don't worry) and we will call it to open by JavaScript:
$('#some-modal').modal();
When this happens, Bootstrap triggers the events called show.bs.modal
and shown.bs.modal
. The first one is called before the open modal call and the other is called after the action. Let's say we want to customize our modal before it is shown. To do this, we must use the first event:
$('#some-modal').on('shown.bs.modal', function(e) { // do some customization before shown });
The events can be used for all plugins. Just change the namespace (in this case, .modal
is the namespace) to achieve the result.