Most of the componants discussed in the previous chapter are just the beginning. Bootstrap comes bundled with 13 jQuery plugins that that extend the features, and can add more interaction to your site. To get started with the Bootstrap Javascript plugins, you don’t need to be an advanced Javascript developer. In fact, most of the plugins can be enacted without writing a single line of code by utilizing the Bootstrap data API.
Bootstrap cand be included on your site in two forms, either compiled or raw. Bootstrap 2.2.2 the uncompressed file is 59kb, and the minimized version is only 32kb. All of the Bootstrap plugins are accessible entirely using the included data API, with this, you don’t need to include a single line of javascript to invoke any of the plugins features.
Typically, Javascript lies in a either a seperate file, or at the bottom of the page before the closing </body>
tag. You can either use the src
atttribute to link to another file, or write the contents of the file between the opening and closing tags.
<!-- To reference another Javascript file -->
<script src="assets/js/javascript.js"></script>
<!-- To write Javascript to the page -->
<script type="text/javascript">
function js_alert{
alert('Page has loaded');
}
</script>
Generally, it is best to include all Javascript calls into check that ensures that the DOM has been loaded on the page. As the browser parses the page, if you have the Javascript trying to fire earlier, it may miss elements. With jQuery, this is easily done by selecting the document
, or the entire content of the page, an then applying the .ready()
method.
$(document).ready(function(){
alert('Page has loaded');
// Once the page has loaded, and is ready, an alert will fire.
});
Like I mentioned above, Bootstrap has a data API where you can write data attributes into the HTML of the page. If you need to turn off the data API, you can unbind the attributes by adding this line of Javascript.
$('body').off('.data-api')
If you need to disable a single plugin, you can do it programmatically using the namespace of the plugin along with the data-api
namespace.
$('body').off('.alert.data-api')
The devlelopers of Bootstrap believe that you should be able to use all of the plugins entirely throught the Javascript API. All public APIs are single, chainable methods, and return the collection acted upon.
$('.btn.danger').button('toggle').addClass('active')
All methods should accept an optional options object, a string which targets a particular method, or nothing (which initiates a plugin with default behavior).
$("#myModal").modal() // initialized with defaults
$("#myModal").modal({ keyboard: false }) // initialized with no keyboard
$("#myModal").modal('show') // initializes and invokes show immediately
The transition plugin provides simple transition effects. A few examples include:
-
Sliding or fading in modals
-
Fading out tabs
-
Fading out alerts
-
Sliding carousel panes
A modal is a child window that layered over its parent window. Typically, the point is to display content from a separate source that can have some interaction without leaving the parent window. They can provide information, interaction, or more for a page.. I have used that as a window for holding slideshows, login/registration information, and more. The Modal plugins is probably one of my favorite Bootstrap features.
To create a static example, use the code below.
<div class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<a href="#" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
To invoke the modal window, you need to have some kind of a trigger. Normally I use a button or an link. If you look in the code below, you will see that the <a>
tag, the href="myModal"
is the target of the modal that you want to load on the page. The allows you to create multiple modals on the page, and then have different triggers for each of them. Now, to be clear, you don’t load multiple modals at the same time, but can create many on the page to be loaded at different times.
There are three classes to take note of in the modal. The first is modal
. This should make sense, but this is identifying the content of the div
as a modal. The second is hide
. This tells the browser to hide the content of the div
until we are ready to invoke it. And last, the fade
class. When the modal is toggled, it will cause the content to fade in and out.
<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
Using the Bootstrap Javascript Data API, you simply need to pass a few data attributes to toggle the slideshow. To start with, set data-toggle="modal"
on the link or button that you want to use to invoke the modal and then data-target="#foo"
to the ID of the modal that you’d like to use.
Using Modal through Javascript
To call a modal with id="myModal"
use a single line of JavaScript:
$('#myModal').modal(options)
Options can either be passed in via data attributes, or with Javascript. To use the data attributes, prepend data-
to the option name, like, data-backdrop=""
.
Name | Type | Default | Description |
---|---|---|---|
backdrop |
boolean |
true |
Set to flase if you don’t want the modal to be closed when they click outside of the modal. |
keyboard |
boolean |
true |
Closes the modal when escape key is pressed, set to false to disable. |
show |
boolean |
true |
Shows the modal when initialized. |
remote |
path |
false |
Using the jQuery |
Activates your content as a modal. Accepts an optional options object.
$('#myModal').modal({
keyboard: false
})
If you need specific events during the firing events of Bootstrap’s modals, you can use the folloing events.
Event | Description |
---|---|
show |
Fired after the |
shown |
Fired when the modal has been made visible to the user. |
hide |
Fired when the |
hidden |
Fired when the modal has finished being hidden from the user. |
$('#myModal').on('hidden', function () {
alert('Hey girl, I heard you like modals...');
})
The dropdown was covered extensively in chapter 3, but then, the interaction was simply glossed over. As a refresher, dropdowns can be added to the the navbar, pills, tabs and buttons.
To use, add use data-toggle="dropdown"
to a link or button to toggle the dropdown.
<li class="dropdown">
<a href="#" id="drop" role="button" class="dropdown-toggle" data-toggle="dropdown">Word <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu" aria-labelledby="drop">
<li><a tabindex="-1" href="#">MAKE magazine</a></li>
<li><a tabindex="-1" href="#">WordPress DevelopmentS</a></li>
<li><a tabindex="-1" href="#">Speaking Engagements</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#">Social Media</a></li>
</ul>
</li>
If you need to keep links entact, useful if the browser is not enabling Javascript, use the data-target
attribute along with href="#"
.
data-target
Attribute<div class="dropdown">
<a class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#" href="/page.html">
Dropdown
<b class="caret"></b>
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
...
</ul>
</div>
To call the dropdown toggle via Javascript, use the following method.
$('.dropdown-toggle').dropdown()
The scrollspy plugin allows you to target sections of the page based on scroll position. In its basic implementation, as you scroll you can add active classes to the nav bar based on the scroll postion. To add the scrollspy plugin via data attributes, add data-spy="scroll"
to the element you want to spy on (most typically this would be the body) and data-target=".navbar"
to the navbar that you want to apply the class changes to. For this to work, you must have elements in the body of the page that have matching ids of the links that you are spying on.
<body data-spy="scroll" data-target=".navbar">...</body>
In the navbar, you will need to have page anchors that will serve as indicators for the element to spy on.
<div class="navbar">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="#">Jake's BBQ</a>
<div class="nav-collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#pork">Pork</a></li>
<li><a href="#beef">Beef</a></li>
<li><a href="#chicken">Chicken</a></li>
</ul>
</div><!-- /.nav-collapse -->
</div>
</div><!-- /navbar-inner -->
</div>
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-offset="".
Name | type | default | description |
---|---|---|---|
offset |
number |
10 |
Pixels to offset from top of page when calculating position of scroll. |
The offset option is handy when you are using a fixed navbar. You will want to offset the scroll by about 50 pixels so that it reads at the correct time.
That tabbable tabs were introduced back in chapter 3. Combing a few data attributes, you can easily create a tabbed interface. To do so, create the nav interface, and then wrap the content of the tabs inside a <div>
with a class of .tab-content
.
<ul class="nav nav-tabs">
<li><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#messages" data-toggle="tab">Messages</a></li>
<li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">...</div>
<div class="tab-pane" id="profile">...</div>
<div class="tab-pane" id="messages">...</div>
<div class="tab-pane" id="settings">...</div>
</div>
To enable the tabs, you can use the Bootstrap Data API, or using Javascript directly. With the Data API, you need to add data-toggle
to the anchors. The anchor targets will activate the the element that has the .tab-pane class and relative ID. Alternatively, data-target=""
may be used instead of href="#"
to apply the same action.
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
})
$('#myTab a[href="#profile"]').tab('show'); // Select tab by name
$('#myTab a:first').tab('show'); // Select first tab
$('#myTab a:last').tab('show'); // Select last tab
$('#myTab li:eq(2) a').tab('show'); // Select third tab (0-indexed)
Event | Description |
---|---|
show |
This event fires on tab show, but before the new tab has been shown. Use |
shown |
This event fires on tab show after a tab has been shown. Use |
$('a[data-toggle="tab"]').on('shown', function (e) {
e.target // activated tab
e.relatedTarget // previous tab
})
For more information about the jQuery .on
method, read more at the jQuery website. jQuery .on
Tooltips are useful when you need to describe a link, or perphaps used in conjuction with the <abbr>
tag, provide the defintion of an abbreviation. The plugin was originally based on the jQuery.tipsy plugin written by Jason Frame. It has since been updated to work without images, animate with a CSS animation, and work with the Bootstrap Javascript API.
<a href="#" rel="tooltip" title="This is the tooltip">Tooltip Example</a>
$('#example').tooltip(options)
Like all of the plugins, there are options that can be added via the Bootstrap Data API, or invoked via Javascript. All options need to have have data-
appended to them. So, the title
option would become data-title
.
Name | type | default | description |
---|---|---|---|
animation |
boolean |
true |
apply a css fade transition to the tooltip |
html |
boolean |
false |
Insert html into the tooltip. If false, jquery’s |
placement |
string/function |
\'top\' |
how to position the tooltip - top/bottom/left/right |
selector |
string |
false |
If a selector is provided, tooltip objects will be delegated to the specified targets. |
title |
string/function |
'' |
default title value if |
trigger |
string |
\'hover\' |
how tooltip is triggered - click |
hover |
focus |
manual |
delay |
The popover is a sibling of the tooltip, offering an entended view, complete with a heading. For the popver to activate, a person just needs to hover over the element. The content of the popver can be populated entirely using the Bootstrap Data API. This method required tooltip.
<a href="#" class="btn" rel="popover" title="Using Popover" data-content="Just add content to the data-content attribute.">Click Me!</a>
All options can be passed via the Boostrap Data API, or directly with Javascript.
Name | type | default | description |
---|---|---|---|
animation | boolean | true | apply a css fade transition to the tooltip |
html | boolean | false | Insert html into the popover. If false, jquery's text method will be used to insert content into the dom. Use text if you're worried about XSS attacks. |
placement | string|function | 'right' | how to position the popover - top | bottom | left | right |
selector | string | false | if a selector is provided, tooltip objects will be delegated to the specified targets |
trigger | string | 'click' | how popover is triggered - click | hover | focus | manual |
title | string | function | '' | default title value if `title` attribute isn't present |
content | string | function | '' | default content value if `data-content` attribute isn't present |
delay | number | object | 0 |
delay showing and hiding the popover (ms) - does not apply to manual trigger type
If a number is supplied, delay is applied to both hide/show
Object structure is: delay: { show: 500, hide: 100 }
|
With the Data APi, it is easy to add dismiss functionality to alert messages.
$(".alert").alert()
<a class="close" data-dismiss="alert" href="#">×</a>
$().alert()
To enable all alerts to be ale to be closed, add the above method. To enable alerts to animate out when closed, make sure they have the .fade
and .in
class already applied to them.
There are two event that can be tied to Bootstrap’s alert class.
Event | Description |
---|---|
close |
This event fires immediately when the close instance method is called. |
closed |
This event is fired when the alert has been closed (will wait for css transitions to complete). |
$('#my-alert').bind('closed', function () {
// do something…
})
Buttons were introduced in chapter 3, and you don’t need to do anything to make them work as links, and as buttons in forms. There is some additional interaction that you can add with the plugin, notably loading states, and adding toolbar like functionality to button groups.
To add a loading state to a button, simply add data-loading-text="Loading…"
as an attribute to the button. When the button is clicked, the .disabled
class is added, giving the apearence that it can no longer be clicked.
<button type="button" class="btn btn-primary" data-loading-text="Loading...">Submit!</button>
When clicking on a button with the data-toggle="button"
attribute, a class of .active
is added.
<button type="button" class="btn btn-primary" data-toggle="button">Toggle</button>
Buttons can work like checkboxes, where you can select many of the options in a button group. To add this function, add data-toggle="buttons-checkbox"
for checkbox style toggling on btn-group
.
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" class="btn btn-primary">Left</button>
<button type="button" class="btn btn-primary">Middle</button>
<button type="button" class="btn btn-primary">Right</button>
</div>
Radio buttons function similarily to checkboxes, the primary difference is that a radio button doesn’t allow for multiple selections, only one in the group. To add this function, add data-toggle="buttons-radio"
for radio style toggling on btn-group
.
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" class="btn btn-primary">Left</button>
<button type="button" class="btn btn-primary">Middle</button>
<button type="button" class="btn btn-primary">Right</button>
</div>
The .button
method can be applied to any class or ID that you want. To enable all buttons in the .nav-tabs
via Javascript, add this code:
$('.nav-tabs').button()
Toggles push state. Gives the button the appearance that it has been activated.
$().button('toggle')
Sets button state to loading - disables button and swaps text to loading text. Loading text should be defined on the button element using the data attribute data-loading-text.
<button type="button" class="btn" data-loading-text="loading stuff..." >...</button>
Resets button state, bringing the original content back to the text. Useful when you need to return the button back to the primary state.
$().button('reset')
String in this method is referring to any string decalred by the user.
$().button('string')
To reset the button state, and bring in new content, use the string method.
<button type="button" class="btn" data-complete-text="finished!" >...</button>
<script>
$('.btn').button('complete')
</script>
The collapse plugin makes it easy to make collapsing divs. Whether you use it to build accordian naviation or content boxes, it allows for a lot of content options.
<div class="accordion" id="accordion2">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
Collapsible Group Item #1
</a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
<div class="accordion-inner">
Anim pariatur cliche...
</div>
</div>
</div>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
Collapsible Group Item #2
</a>
</div>
<div id="collapseTwo" class="accordion-body collapse">
<div class="accordion-inner">
Anim pariatur cliche...
</div>
</div>
</div>
</div>
...
You can also use the data attributes to make all content collapsable.
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#demo">
simple collapsible
</button>
<div id="demo" class="collapse in"> … </div>
Like all of the plugins that use the data attributes API, you can add all needed markup without writing any Javascript. Add data-toggle="collapse"
and a data-target
to the element to automatically assign control of a collapsible element. The data-target
attribute will accept a css selector to apply the collapse to. Be sure to add the class .collapse
to the collapsible element. If you’d like it to default open, add the additional class .in
.
To add accordion-like group management to a collapsible control, add the data attribute data-parent="#selector".
Options can be passed via data attributes, or with Javascript.
Name | type | default | description |
---|---|---|---|
parent |
selector |
false |
If selector then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior) |
toggle |
boolean |
true |
Toggles the collapsible element on invocation |
Activates your content as a collapsible element. Accepts an optional options object.
.collapse(options)
Toggles a collapsible element to shown or hidden.
$('#myCollapsible').collapse({
toggle: false
})
.collapse('toggle')
There are four events that can be hooked into with the collapse plugin.
Event | Description |
---|---|
show |
This event fires immediately when the |
shown |
This event is fired when a collapse element has been made visible to the user (will wait for css transitions to complete). |
hide |
This event is fired immediately when the |
hidden |
This event is fired when a collapse element has been hidden from the user (will wait for css transitions to complete). |
$('#myCollapsible').on('hidden', function () {
// do something…
})
The Bootstrap carousel is a flexible, responsive way to add a slider to your site. In addiotn to being responsive, the content is flexible enough to allow images, iframes, video, or likely anytime of content that you might want.
<div id="myCarousel" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="active item">…</div>
<div class="item">…</div>
<div class="item">…</div>
</div>
<!-- Carousel nav -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
To implement the carousel, you just need to add the code with the markup above. No need for data atrributes, just simple class based development. To call the carousel with Javascript, you can do it manually with the following code:
$('.carousel').carousel()
Options can be passed through data attributes, or through Javascript.
Name | type | default | description |
---|---|---|---|
interval |
number |
5000 |
The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle. |
pause |
string |
"hover" |
Pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave. |
Initializes the carousel with an optional options object and starts cycling through items.
$('.carousel').carousel({
interval: 2000
})
Typeahead allows you to easily create typeahead inputs in forms. Example, you could preload states in a state field, or using some Javascript, get search results using some ajax calls.
Using data API, you can add sources via the data-source
attribute. Items should be listed in either a JSON array, or a function.
<input
type="text"
class="span3"
data-provide="typeahead"
data-items="4"
data-source="[
'Alabama',
'Alaska',
'Arizona',
'Arkansas',
'California',
...
]"
>
To call directly with Javascript, use the following method.
$('.typeahead').typeahead()
Name | type | default | description |
---|---|---|---|
source |
array, function |
[ ] |
The data source to query against. May be an array of strings or a function. The function is passed two arguments, the |
items |
number |
8 |
The max number of items to display in the dropdown. |
minLength |
number |
1 |
The minimum character length needed before triggering autocomplete suggestions |
matcher |
function |
case insensitive |
The method used to determine if a query matches an item. Accepts a single argument, the item against which to test the query. Access the current query with |
sorter |
function |
exact match, case sensitive, case insensitive |
Method used to sort autocomplete results. Accepts a single argument items and has the scope of the typeahead instance. Reference the current query with |
updater |
function |
returns selected item |
The method used to return selected item. Accepts a single argument, the item and has the scope of the typeahead instance. |
highlighter |
function |
highlights all default matches |
Method used to highlight autocomplete results. Accepts a single argument item and has the scope of the typeahead instance. Should return html. |
The affix plugin allows you to allow a div
to become affixed to a location on the page. A common example of this is social icons on a page. They will start in a location, but as the page hits a certain mark, the div
will become locked in place and will stop scrolling with the rest of the page.
To apply the affix plugin to a div
, you can use either data attributes, or use Javascript directly. Of note, you must position the element so that it can be affixed to the page. Position is controlled by the data-spy
attribute, using either affix
, affix-top
, or affix-bottom
. You then use the data-offset
to calcualte the position of the scroll.
<div data-spy="affix" data-offset-top="200">
...
</div>
Name | type | default | description |
---|---|---|---|
offset |
number/function/object |
10 |
Pixels to offset from screen when calculating position of scroll. If a single number is provided, the offset will be applied in both top and left directions. To listen for a single direction, or multiple unique offsets, just provide an object |