Hour 14. Using Bootstrap JavaScript Plugins


What You’ll Learn in This Hour:

Image How to add Bootstrap JavaScript plugins

Image How to set options for the plugins

Image How to use the JavaScript API

Image How to prevent some common problems with the Bootstrap plugins


In Part II, “Building and Managing Web Pages with Bootstrap,” you learned a lot about the various CSS styles and components that Bootstrap provides. But Bootstrap also includes more than 10 JavaScript plugins you can use to add interactivity and dynamic elements to your website. In this hour you learn how to use the plugins as well as the API so you can program your own plugins with special features. In the following hours in Part III, you will learn more specifics about the different plugins and how to use them.

How to Use Bootstrap JavaScript Plugins

The first step when using any of the Bootstrap plugins is to include the JavaScript file. There are three ways to include the JavaScript:

Image Include the compiled, minified JavaScript file <script src="js/bootstrap.min.js"></script>

Image Include the compiled, non-minified JavaScript file <script src="js/bootstrap.js"></script>

Image Include only the plugin you want to use <script src="js/dropdown.js"></script>

Include the JavaScript once at the very bottom of your document, just above the </html> tag. Make sure that your src attribute points to the correct location and filename.


Note: Best Practice: Use the Minified Full Script File

Unless your website requires extreme download speeds, it’s best to include the minified compiled JavaScript file, rather than including each plugin separately. This ensures that you always have the scripts ready if you add a new feature to the page, and the minified version is only 35KB, so it will still download fairly quickly.


After you have the Bootstrap JavaScript installed, you need to include jQuery as well. All the plugins require jQuery, so you should include a call to it just before the Bootstrap JavaScript. Bootstrap 3.3.2 requires jQuery 1.9.1 or higher. Listing 14.1 shows how the bottom of a typical Bootstrap document looks.

LISTING 14.1 The Bottom of a Bootstrap Document


<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>


Setting Options for Plugins

Many of the plugins that Bootstrap offers include options so you can modify how the plugin works on your pages. The two ways you can include these options are

Image Send the options as parameters in JavaScript method

Image Use data attributes in the HTML

Both of these methods work equally well, and there are good reasons for using both in your websites. If you are comfortable writing JavaScript, you might find parameters easier, while data attributes require less knowledge of programming. Many Bootstrap sites use a combination of both to set the options.

Options as Parameters

If you’re building the plugin completely in the JavaScript, this is a reasonable method to use. You trigger the plugin with JavaScript and include the options as a JSON array. Listing 14.2 shows how.

LISTING 14.2 Setting Options as Parameters


$('#example').tooltip({
  html:true,
  delay: 200,
  trigger:"click"
});


Listing 14.2 sets a tooltip (see Hour 17, “Popovers and Tooltips”) with the options for HTML delivery, a delay of 200ms, and the trigger as a click. You also could put those options in an array variable and pass them that way.

Bootstrap plugins use JSON arrays to store the options data. If you want to learn more about JSON, you should visit the JSON website http://json.org/.

Options as Data Attributes

If the previous section with arrays, variables, JSON, and so on makes you nervous, you can relax because you don’t need any of it to use Bootstrap plugins. Instead, you can use data attributes to assign the options to the plugins.

A data attribute is a new feature of HTML5. They are attributes on HTML elements that start with the word data- and then are followed by the name of the data attribute.


Caution: Data Attributes May Not Validate

If you use HTML validators to check your HTML, you may get error messages saying that the data-* attributes you use for Bootstrap plugins are not valid. Be sure that your web page uses the HTML5 doctype <!doctype html>; if you still get validation errors specific to the data-* attributes, you should ignore them or consider using a different HTML validator.


For example, in the Listing 14.2 tooltip, there was an option called delay. To set this option with data attributes, you would add an attribute to the tooltip element called data-delay. Listing 14.3 shows a button that includes a tooltip with the same options as in Listing 14.2, but the options are set with data attributes.

LISTING 14.3 Options Set with Data Attributes


<button type="button" class="btn btn-default" data-toggle="tooltip"
        data-html="true" data-delay="200" data-trigger="click"
        title="You did it!">
  Click to toggle Tooltip
</button>


As shown in Figure 14.1, the tooltip displays without any JSON or JavaScript variables or arrays.

Image

FIGURE 14.1 A tooltip using data attributes.

Data attributes should always be your first consideration when using Bootstrap plugins. They are easy to use, and placing the options right on the HTML element that defines the plugins makes the page easier to maintain. To look at the button example in Listing 14.2; it’s obvious that a tooltip is assigned to this button because of the data-toggle="tooltip" attribute. As you look closer at the element, you know that the tooltip will have HTML results, have a delay of 200ms, and be triggered by a click. And if you want to change those options, you can do so right in the HTML.

But there are some problems with data attributes, including these:

Image You can have only one plugin per element. In other words, your button cannot trigger both a tooltip and a modal. If you need to do that, you will need to wrap an element around the first element and attach the second plugin to that.

Image You can set the options for only one element at a time. If you want to set every tooltip to display in HTML with a 200ms delay, you must add those data attributes to every element that has a tooltip.

Image You cannot use complex JSON options in data attributes. For example, you might want to set the show delay on the tooltip to 200ms but the hide delay to 500ms. With JavaScript, you would set your option to delay: { "show": 200, "hide": 500 }. But there is no way to do that in Bootstrap. If you need to do that, you have to modify the bootstrap.js file.

If your website needs to have the data attributes disabled, you can do that as well. You add $(document).off('.data-api') to your document scripts, as shown in Listing 14.4.

LISTING 14.4 Turn Off Data Attributes


...
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
  $(document).off('.data-api')
</script>
</body>
</html>


You also can turn off data attributes for specific plugins by including that plugin’s name as a namespace along with the data-api namespace. For instance, to turn off data attributes for tooltips, you would write $(document).off('.tooltip.data-api').

Using the JavaScript API

Bootstrap is designed to also use the JavaScript plugins through the JavaScript API. They have set up all the APIs as single, chainable methods that return the collection acted upon.

This means you can access the plugins from within your scripts and add them to other elements as you need them. For example, Listing 14.5 shows how you might add a tooltip to a button with an ID of #myToolTip.

LISTING 14.5 Add a Tooltip Programmatically


$('#myToolTip').tooltip('toggle');


All the Bootstrap methods accept three values:

Image Nothing—For example, tooltip(). This indicates that the method should be initialized with the defaults.

Image An options object—For example, tooltip( { html: true } ). This acts just like data attributes for setting the option values.

Image A string targeting a particular method—For example, tooltip('toggle'). This initializes the tooltip with the toggle method invoked immediately.

You learn more about the specific options for each plugin in the following hours.

If you need access to the raw constructor for the plugin, it is available in the Constructor property—for example, $.fn.tooltip.Constructor. You also can use the Constructor property to change the default settings for a plugin. Listing 14.6 shows how you modify the Constructor.DEFAULTS object to change the default value.

LISTING 14.6 Change Tooltips to Default to HTML True


$.fn.tooltip.Constructor.DEFAULTS.html = true;


You can get the version number of the plugin with the Constructor.VERSION object—for example, $.fn.tooltip.Constructor.VERSION.

Events

Bootstrap provides custom events for most of the plugins. These are named in the infinitive (show) and past participle (shown) forms. The infinitive is triggered at the start of an event, and the past participle is triggered when the action is completed.

All Bootstrap events are namespaced as of version 3.0.0.

You also can stop an event before it starts with the preventDefault functionality. Listing 14.7 shows how you might do this.

LISTING 14.7 Preventing an Event with preventDefault


$('#myModal').on('show.bs.modal', function (e) {
  if (!data) return e.preventDefault() // stops modal showing
})


No Conflict

Sometimes you might want to use Bootstrap with another UI framework. This can cause conflicts if both Bootstrap and the other framework use the same names for things. To solve this, you can call .noConflict on the plugin you want to revert the value of. Then you can reassign the values to a nonconflicting name. Listing 14.8 shows how.

LISTING 14.8 Using .noConflict on a Button


// return $.fn.button to previously assigned value
var bootstrapButton = $.fn.button.noConflict();
// give $().bootstrapBtn the Bootstrap functionality
$.fn.bootstrapBtn = bootstrapButton;



Caution: Bootstrap Does Not Support Third-Party Libraries

Although Bootstrap has the .noConflict method and namespaced events, Bootstrap does not guarantee that these will work with third-party libraries and other frameworks. If you must use an additional library such as jQuery UI, you will have to test it and fix any problems you find on your own.


Disabled JavaScript

On very rare occasions your customers might disable JavaScript. Bootstrap is designed to work with JavaScript, and the plugins will not work if JavaScript is turned off.

When a customer with JavaScript turned off visits a page with a Bootstrap plugin, she might get strange results or see nothing at all. If you need to, you can use the <noscript></noscript> element to provide additional information, such as how to enable JavaScript. You also can create your own custom fallbacks for when JavaScript is disabled or turned off.

Summary

In this hour, you learned about how Bootstrap JavaScript plugins work. You learned what you need to do to install and use the plugins as well as how to set options for the plugins in several different ways.

This hour covered how to use the JavaScript API, including changing the default values, getting the plugin version, and triggering plugin events. You also learned about two possible problems—conflicts with other frameworks and disabled JavaScript—and how to solve them.

Workshop

The workshop contains quiz questions to help you process what you’ve learned in this hour. Try to answer all the questions before you read the answers.

Q&A

Q. What if I don’t want to use any plugins on my pages?

A. If you don’t use any plugins, then you don’t need to include the Bootstrap JavaScript files or jQuery in your HTML. But by including them, you prepare your pages for the future if you do decide to add a plugin.

Q. I’m concerned about speed of downloading. Don’t these plugins make the pages take longer?

A. Anything you add to your page is going to incrementally increase the download time. JavaScript, because it cannot load in parallel with any other element, can increase the time even more. But there are many things you can do to decrease this load time:

Image Use the minified JavaScript files—The full file is only 35KB.

Image Use only the plugin scripts you need—You will learn more about how to do this in Hour 21, “Customizing Bootstrap and Your Bootstrap Website.”

Image Always place the JavaScript at the bottom of your documents—This ensures that the rest of the page has loaded before the scripts start to download, thus making the page visible faster for your readers.

Image Use cached copies of the scripts—By loading the script files from a content delivery network (CDN), you take advantage of web caches and help your files load more quickly. In the code samples in this hour, jQuery is installed from a CDN. You can even load Bootstrap from a CDN, such as the Microsoft Ajax Content Delivery Network (http://www.asp.net/ajax/cdn#Bootstrap_Releases_on_the_CDN_14).

Quiz

1. Which of these is not a way to include Bootstrap plugins?

a. Include the full bootstrap.js file.

b. Include the minified script file.

c. Include the plugin JavaScript file.

d. None of the above.

2. True or False: jQuery is an optional tool for using the Bootstrap plugins.

3. What is the best way to add options to plugins?

a. As parameters

b. As data attributes

c. As script variables

d. However works best for your page and your skills

4. How are parameters written?

a. As a variable

b. As an array

c. As a JSON array

d. As plain text

5. How do you add a data attribute?

a. Add the tag <data> surrounding the information.

b. Add an attribute called data-* with the name of the data (that is, data-show) to the HTML tag.

c. Include the data in a meta-data attribute.

d. Add an attribute with the name of the data (that is, show) to the HTML tag.

6. In this HTML, what is setting the option to open the tooltip after a lag?

<button type="button" class="btn btn-default" data-toggle="tooltip"
data-html="true" data-delay="200" data-trigger="click"
title="You did it!">

a. data-toggle="tooltip"

b. data-delay="200"

c. data-trigger="click"

d. title="You did it!"

7. Is this a valid way to add a tooltip?

$('#myToolTip').tooltip();

a. Yes

b. No

8. What does this line of code do?

$.fn.tooltip.Constructor.DEFAULTS.placement = 'bottom';

a. Verifies that the tooltip placement default option is bottom

b. Changes the tooltip placement default option to bottom

c. Creates a new tooltip option called placement with a default of bottom

d. Returns any tooltip options that are given the default value bottom

9. How do you return the version number of the dropdown plugin?

a. $.fn.tooltip.Constructor.VERSION

b. $.fn.dropdown.constructor.VERSION

c. $.fn.dropdown.Constructor.VERSION

d. $.fn.dropdown.Constructor.Version

10. How does Bootstrap handle a customer that doesn’t have JavaScript?

a. Bootstrap has an automatic fallback telling the customer to turn on JavaScript.

b. Bootstrap has specific fallback options that are different for each plugin.

c. Bootstrap forces the browser to turn on JavaScript.

d. Bootstrap does nothing.

Quiz Answers

1. d. All of the answers are correct ways to include Bootstrap plugins.

2. False. You must include jQuery to use Bootstrap plugins.

3. d. There is no one best way to include options for Bootstrap plugins. You should use the method that works best for your scripts, your website, and your skills.

4. c. As a JSON array.

5. b. Add an attribute called data-* with the name of the data (that is, data-show) to the HTML tag.

6. b. data-delay="200"

7. a. Yes, it uses the Bootstrap API to add the tooltip directly to an element in the DOM.

8. b. Changes the tooltip placement default option to bottom.

9. c. $.fn.dropdown.Constructor.VERSION

10. d. Bootstrap does nothing. JavaScript is required to run Bootstrap plugins, but if it’s not enabled, there is no fallback option. You have to build fallbacks yourself.

Exercises

Start considering what interactivity you are going to want on your website. Bootstrap offers features like tooltips, modals, dropdown menus, alerts, pop-overs, and much more. If you are not familiar with jQuery, you should consider learning how it is structured. A good book to start with is Sams Teach Yourself JavaScript and jQuery in 24 Hours by Brad Dayley.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.153