Table of Contents for
Bootstrap 4 – Responsive Web Design

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Bootstrap 4 – Responsive Web Design by Jason Marah Published by Packt Publishing, 2017
  1. Cover
  2. Table of Contents
  3. Bootstrap 4 – Responsive Web Design
  4. Bootstrap 4 – Responsive Web Design
  5. Credits
  6. Preface
  7. What you need for this learning path
  8. Who this learning path is for
  9. Reader feedback
  10. Customer support
  11. 1. Module 1
  12. 1. Getting Started
  13. Setting up the framework
  14. Building our first Bootstrap example
  15. Optionally using the CDN setup
  16. Community activity
  17. Bootstrap and web applications
  18. Browser compatibility
  19. Summary
  20. 2. Creating a Solid Scaffolding
  21. Building our scaffolding
  22. Fluid container
  23. We need some style!
  24. Manipulating tables
  25. Like a boss!
  26. Final thoughts
  27. Summary
  28. 3. Yes, You Should Go Mobile First
  29. Bootstrap and the mobile-first design
  30. How to debug different viewports at the browser
  31. Cleaning up the mess
  32. Creating the landing page for different devices
  33. Summary
  34. 4. Applying the Bootstrap Style
  35. Summary
  36. 5. Making It Fancy
  37. Paying attention to your navigation
  38. Dropping it down
  39. Making an input grouping
  40. Getting ready for flexbox!
  41. Summary
  42. 6. Can You Build a Web App?
  43. Adding the navigation
  44. Do a grid again
  45. Playing the cards
  46. Implementing the main content
  47. Creating breadcrumbs
  48. Finishing with the right-hand-side content
  49. Summary
  50. 7. Of Course, You Can Build a Web App!
  51. Waiting for the progress bar
  52. Creating a settings page
  53. Summary
  54. 8. Working with JavaScript
  55. Awesome Bootstrap modals
  56. Creating our custom modal
  57. A tool for your tip
  58. Pop it all over
  59. Making the menu affix
  60. Finishing the web app
  61. Summary
  62. 9. Entering in the Advanced Mode
  63. The last navigation bar with flexbox
  64. Filling the main fluid content
  65. Filling the main content
  66. Overhead loading
  67. Fixing the toggle button for mobile
  68. Summary
  69. 10. Bringing Components to Life
  70. Fixing the mobile viewport
  71. Learning more advanced plugins
  72. Summary
  73. 11. Making It Your Taste
  74. Working with plugin customization
  75. The additional Bootstrap plugins
  76. Creating our Bootstrap plugin
  77. Defining the plugin methods
  78. Creating additional plugin methods
  79. Summary
  80. 2. Module 2
  81. 1. Introducing Bootstrap 4
  82. Summary
  83. 2. Using Bootstrap Build Tools
  84. Download the Bootstrap source files
  85. Setting up the blog project
  86. Setting up the JSON files
  87. Creating our first page template
  88. Summary
  89. 3. Jumping into Flexbox
  90. Ordering your Flexbox
  91. Wrapping your Flexbox
  92. Setting up the Bootstrap Flexbox layout grid
  93. Setting up a Flexbox project
  94. Designing a single blog post
  95. Summary
  96. 4. Working with Layouts
  97. Inserting rows into your layout
  98. Adding columns to your layout
  99. Choosing a column class
  100. Creating a simple three-column layout
  101. Mixing column classes for different devices
  102. Coding the blog home page
  103. Using responsive utility classes
  104. Summary
  105. 5. Working with Content
  106. Learning to use typography
  107. Customizing headings
  108. How to style images
  109. Coding tables
  110. Summary
  111. 6. Playing with Components
  112. Basic button examples
  113. Creating outlined buttons
  114. Checkbox and radio buttons
  115. Coding forms in Bootstrap 4
  116. Creating an inline form
  117. Adding validation to inputs
  118. Using the Jumbotron component
  119. Adding the Label component
  120. Using the Alerts component
  121. Using Cards for layout
  122. Updating the Blog index page
  123. How to use the Navs component
  124. Adding Breadcrumbs to a page
  125. Using the Pagination component
  126. How to use the List Group component
  127. Summary
  128. 7. Extending Bootstrap with JavaScript Plugins
  129. Coding Tooltips
  130. Avoiding collisions with our components
  131. Using Popover components
  132. Using the Collapse component
  133. Coding an Accordion with the Collapse component
  134. Coding a Bootstrap Carousel
  135. Summary
  136. 8. Throwing in Some Sass
  137. Using Sass in the blog project
  138. Importing partials in Sass
  139. Creating a collection of variables
  140. Customizing components
  141. Writing a theme
  142. Summary
  143. 9. Migrating from Version 3
  144. Big changes in version 4
  145. Updating your variables
  146. Additional global changes
  147. Other font updates
  148. Migrating components
  149. Migrating JavaScript
  150. Miscellaneous migration changes
  151. Summary
  152. 3. Module 3
  153. 1. Revving Up Bootstrap
  154. What Bootstrap 4 Alpha 4 has to offer
  155. Setting up our project
  156. Summary
  157. 2. Making a Style Statement
  158. Image elements
  159. Responsive utilities
  160. Helper classes
  161. Text alignment and transformation
  162. Summary
  163. 3. Building the Layout
  164. Adding Bootstrap components
  165. Summary
  166. 4. On Navigation, Footers, Alerts, and Content
  167. Improving navigation using Scrollspy
  168. Customizing scroll speed
  169. Icons
  170. Using and customizing alerts
  171. Creating a footer
  172. Creating and customizing forms
  173. Form validation
  174. Progress indicators
  175. Adding content using media objects
  176. Figures
  177. Quotes
  178. Abbreviations
  179. Summary
  180. 5. Speeding Up Development Using jQuery Plugins
  181. Enhanced pagination using bootpag
  182. Displaying images using Bootstrap Lightbox
  183. Improving our price list with DataTables
  184. Summary
  185. 6. Customizing Your Plugins
  186. Customizing plugins
  187. Writing a custom Bootstrap jQuery plugin
  188. Summary
  189. 7. Integrating Bootstrap with Third-Party Plugins
  190. Hover
  191. Summary
  192. 8. Optimizing Your Website
  193. Minifying CSS and JavaScript
  194. Introducing Grunt
  195. Running tasks automatically
  196. Stripping our website of unused CSS
  197. JavaScript file concatenation
  198. Summary
  199. 9. Integrating with AngularJS and React
  200. Introducing React
  201. Summary
  202. Bibliography
  203. Index

Chapter 6. Customizing Your Plugins

So far, we have built the MyPhoto demo page leveraging all that Bootstrap has to offer, customizing Bootstrap's themes and components, and using jQuery plugins along the way. In this chapter, we will be delving deep into Bootstrap's jQuery plugins with extensive customization via JavaScript and CSS.

We will take some of the plugins we have introduced into MyPhoto, take a look under the hood, and, step by step, we will customize them to meet the needs of our page. Plugins will be examined and extended throughout this chapter in an effort to not only make our page better, but to also build our knowledge of how jQuery plugins are built and behave within Bootstrap's ecosystem.

When we are comfortable with customizing Bootstrap's jQuery plugins, we will create a fully customized jQuery plugin of our own for MyPhoto.

Summarizing all of this, in this chapter we will globally do the following:

  • Learn about the anatomy of a Bootstrap jQuery plugin
  • Learn how to extensively customize the behavior and features of Bootstrap's jQuery plugins via JavaScript
  • Learn how to extensively customize the styling of Bootstrap's jQuery plugins via CSS
  • Learn how to create a custom Bootstrap jQuery plugin from scratch

Anatomy of a plugin

Bootstrap jQuery plugins all follow the same convention in how they are constructed. At the top level, a plugin is generally split across two files, a JavaScript file and a Sass file. For example, the Alert component is made up of bootstrap/js/alert.js and bootstrap/scss/_alert.scss. These files are compiled and concatenated as part of Bootstrap's distributable JavaScript and CSS files. Let us look at these two files in isolation to learn about the anatomy of a plugin.

JavaScript

Open up any JavaScript file in bootstrap/js/src, and you will see that they all follow the same pattern: an initial setup, a class definition, data API implementation, and jQuery extension. Let's take a detailed look at alert.js.

Setup

The alert.js file, written in ECMAScript 2015 syntax (also known as ES6, the latest (at the time of writing) standardized specification of JavaScript), first imports a utilities module:

    import Util from './util'

A constant is then created, named Alert, which is assigned the result of an Immediately Invoked Function Expression (IIFE):

    const Alert = (($) => {
    ...
    })(jQuery)

A jQuery object is being passed into a function for execution, the result of which will be assigned to the immutable Alert constant.

Within the function itself, a number of constants are also declared for use throughout the rest of the code. Declaring immutables at the beginning of the file is generally seen as best practice. Observe the following code:

    const NAME                = 'alert'
    const VERSION             = '4.0.0-alpha'
    const DATA_KEY            = 'bs.alert'
    const EVENT_KEY           = '.${DATA_KEY}'
    const DATA_API_KEY        = '.data-api'
    const JQUERY_NO_CONFLICT  = $.fn[NAME]
    const TRANSITION_DURATION = 150
    
    const Selector = {
      DISMISS : '[data-dismiss="alert"]'
    }
    const Event = {
      CLOSE : 'close${EVENT_KEY}',
      CLOSED : 'closed${EVENT_KEY}',
      CLICK_DATA_API : 'click${EVENT_KEY}${DATA_API_KEY}'
    }
    
    const ClassName = {
      ALERT : 'alert',
      FADE : 'fade',
      IN : 'in'
    }

The NAME property is the name of the plugin, and VERSION defines the version of the plugin, which generally correlates to the version of Bootstrap. DATA_KEY, EVENT_KEY, and DATA_API_KEY relate to the data attributes that the plugin hooks into, while the rest are coherent, more readable, aliases for the various values used throughout the plugin code. Following that is the class definition.

Note

Immediately Invoked Function Expression

An Immediately Invoked Function Expression (IIFE or iffy) is a function which is executed as soon as it has been declared, and is known as a self-executing function in other languages. A function is declared as an IIFE by either wrapping the function in parentheses or including a preceding unary operator, and including a trailing pair of parentheses. Examples:

(function(args){ })(args)
!function(args){ }(args)

Class definition

Near the top of any of the plugin JS files, you will see a comment declaring the beginning of the class definition for that particular plugin. In the case of alerts, it is:

    /**
    * -------------------------------------------------------------------
    -----    
    * Class Definition
    * -------------------------------------------------------------------
    -----
    */

The class definition is simply the constructor of the base object, in this case, the Alert object:

    class Alert {
        constructor(element) {
            this._element = element
        }
        ...
    }

The convention with plugins is to use Prototypal inheritance. The Alert base object is the object all other Alert type objects should extend and inherit from. Within the class definition, we have the public and private functions of the Alert class. Let's take a look at the public close function:

    close(element) {
        element = element || this._element
        let rootElement = this._getRootElement(element)
        let customEvent = this._triggerCloseEvent(rootElement)
        if (customEvent.isDefaultPrevented()) {
          return
        }
        
        this._removeElement(rootElement)
    }

The close function takes an element as an argument, which is the reference to the DOM element the close function is to act upon. The close function uses the private function _getRootElement to retrieve the specific DOM element, and _triggerCloseEvent to reference the specific event to be processed. Finally, close calls _removeElement. Let's take a look at these private functions:

    _getRootElement(element) {
        let selector = Util.getSelectorFromElement(element)
        let parent   = false
        
        if (selector) {
            parent = $(selector)[0]
        }
        
        if (!parent) {
            parent = $(element).closest(`.${ClassName.ALERT}`)[0]
        }
        return parent
    }

The _getRootElement tries to find the parent element of the DOM element passed to the calling function, in this case, close. If a parent does not exist, _getRootElement returns the closest element with the class name defined by ClassName.ALERT in the plugin's initial setup. This in our case is Alert. Observe the following code:

    _triggerCloseEvent(element) {
        let closeEvent = $.Event(Event.CLOSE)
        $(element).trigger(closeEvent)
        return closeEvent
    }

The _triggerCloseEvent also takes an element as an argument and triggers the event referenced in the plugin's initial setup by Event.CLOSE:

    _removeElement(element) {
        $(element).removeClass(ClassName.IN)
        if (!Util.supportsTransitionEnd() ||
            !$(element).hasClass(ClassName.FADE)) {
          this._destroyElement(element)
          return
        }
        $(element)
            .one(Util.TRANSITION_END, $.proxy(this._destroyElement,
            this, element))
            .emulateTransitionEnd(TRANSITION_DURATION)
    }

The _removeElement then carries out the removal of the rootElement safely and in accordance with the configuration in the element itself, or as defined in the plugin's initial setup, for example, TRANSITION_DURATION.

All core behaviors and functions of the plugin should be defined in the same manner as the close function. The class definition represents the plugin's essence.

After the public and private functions come the static functions. These functions, which are also private, are similar to what would be described as the plugin definition in Bootstrap 3. Observe the following code:

    static _jQueryInterface(config) {
        return this.each(function () {
            let $element = $(this)
            let data = $element.data(DATA_KEY)
            if (!data) {
                data = new Alert(this)
                $element.data(DATA_KEY, data)
            }
            if (config === 'close') {
                data[config](this)
            }
        })
    }
    static _handleDismiss(alertInstance) {
        return function (event) {
            if (event) {
                event.preventDefault()
            }
            alertInstance.close(this)
        }
    }

The _jQueryInterface is quite simple. First, it loops through an array of DOM elements. This array is represented here by the this object. It creates a jQuery wrapper around each element and then creates the Alert instance associated with this element, if it doesn't already exist. _jQueryInterface also takes in a config argument. As you can see, the only value of config that _jQueryInterface is concerned with is 'close'. If config equals 'close', then the Alert will be closed automatically.

_handleDismiss simply allows for a specific instance of Alert to be programmatically closed.

Following the class definition, we have the data API implementation.

Data API implementation

The role of the data API implementation is to create JavaScript hooks on the DOM, listening for actions on elements with a specific data attribute. In alert.js, there is only one hook:

    $(document).on(
        Event.CLICK_DATA_API,
        Selector.DISMISS,
        Alert._handleDismiss(new Alert())
    )
    $(document).on('click.bs.alert.data-api', dismiss,
    Alert.prototype.close)

The hook is an on-click listener on any element that matches the dismiss selector.

When a click is registered, the close function of Alert is invoked. The dismiss selector here has actually been defined at the beginning of the file, in the plugin setup:

    const Selector = {
        DISMISS : '[data-dismiss="alert"]'
    }

Therefore, an element with the attribute data-dismiss="alert" will be hooked in, to listen for clicks. The click event reference is also defined in the setup:

    const Event = {
        CLOSE          : 'close${EVENT_KEY}',
        CLOSED         : 'closed${EVENT_KEY}',
        CLICK_DATA_API : 'click${EVENT_KEY}${DATA_API_KEY}'
    }

EVENT_KEY and DATA_API_KEY, if you remember, are also defined here:

    const DATA_KEY             = 'bs.alert'
    const EVENT_KEY          = '.${DATA_KEY}'
    const DATA_API_KEY     = '.data-api'

We could actually rewrite the API definition to read as follows:

    $(document).on('click.bs.alert.data-api', '[data-dismiss="alert"]', 
    Alert._handleDismiss(new Alert()))

The last piece of the puzzle is the jQuery section, which is a new feature in Bootstrap 4. It is a combination of Bootstrap 3's plugin definition and a conflict prevention pattern.

jQuery

The jQuery section is responsible for adding the plugin to the global jQuery object so that it is made available anywhere in an application where jQuery is available. Let's take a look at the code:

    $.fn[NAME]             = Alert._jQueryInterface
    $.fn[NAME].Constructor = Alert
    $.fn[NAME].noConflict  = function () {
        $.fn[NAME] = JQUERY_NO_CONFLICT
        return Alert._jQueryInterface
    }

The first two assignments extend jQuery's prototype with the plugin function. As Alert is created within a closure, the constructor itself is actually private. Creating the Constructor property on $.fn.alert allows it to be accessible publicly.

Then, a property of $.fn.alert called noConflict is assigned the value of Alert._jQueryInterface. The noConflict property comes into use when trying to integrate Bootstrap with other frameworks to resolve issues with two jQuery objects with the same name. If in some framework the Bootstrap Alert got overridden, we could use noConflict to access the Bootstrap Alert and assign it to a new variable:

    $.fn.bsAlert = $.fn.alert.noConflict()

$.fn.alert is the framework version of Alert, but we have transferred the Bootstrap Alert to $.fn.bsAlert.

All plugins tend to follow the pattern of initial setup, class definition, data API implementation, and jQuery extension. To accompany the JavaScript, a plugin also has its own specific Sass style sheet.

Sass

Sass files for plugins aren't as formulaic as the corresponding JavaScript. In general, JavaScript hooks into classes and attributes to carry out a generally simple functionality. In a lot of cases, much of the functionality is actually controlled by the style sheet; the JavaScript simply adds and removes classes or elements under certain conditions. The heavy lifting is generally carried out by the Sass, so it is understandable that the Sass itself may not fit into a uniform pattern.

Let's take a look at scss/_alert.scss. The _alert.scss opens up with a base style definition. Most, but not all, plugins will include a base definition (usually preceded by a base style or base class comment). Defining the base styles of a plugin at the beginning of the Sass file is best practice for maintainability and helps anyone who might want to extend the plugin to understand it.

Following the base styles, the styles associated with, or responsible for, the functionality of the plugin are defined. In the case of alerts, the dismissible alert styles are defined. The only piece of functionality an alert has, besides being rendered on the page, is to be dismissed. This is where Alerts defines what should happen when the close class is applied to an Alerts element.

The Sass will also generally include an alternate style definition. The alternate styles generally align with Bootstrap's contextual classes, which we explored in Chapter 2, Making a Style Statement. Observe the following code:

    // Alternate styles
    //
    // Generate contextual modifier classes for colorizing the alert.
    .alert-success {
        @include alert-variant($alert-success-bg, $alert-success-border,
        $alert-success-text);
    }
    .alert-info {
        @include alert-variant($alert-info-bg, $alert-info-border, 
        $alert-info-text);
    }
    .alert-warning {
        @include alert-variant($alert-warning-bg, $alert-warning-border,
        $alert-warning-text);
    }
    .alert-danger {
        @include alert-variant($alert-danger-bg, $alert-danger-border, 
        $alert-danger-text);
    }

As you can see, alert provides styles to correspond with the success, info, warning, and danger contexts. The variables used in the rules, such as $alert-danger-bg, are declared in _variables.scss. Declaring variables in a _variables.scss file is best practice, as otherwise maintenance would be supremely difficult. For instance, open up _variables.scss and see the definition for $alert-danger-bg:

    $alert-warning-bg: $state-warning-bg !default;

The $state-warning-bg is another variable, but this variable is used for all form feedback and alert warning background variables. If we wanted to change the color that the warning context corresponds to, we would just need to change the value in one place:

    $state-warning-bg: #fcf8e3 !default;

Beyond the base styles and, to an extent, the alternate styles, there is no real template for plugging in the Sass files.

The JavaScript file and the Sass file are the two ingredients that make a plugin work. Looking at the example from Chapter 4, On Navigation, Footers, Alerts, and Content,we can see the alert plugin in action:

    <div class="alert alert-danger">
        <a href="#" class="close" data-dismiss="alert" 
        aria-label="close">&times;</a>
        <strong class="alert-heading"><i class="fa fa-
        exclamation"></i> Unsupported browser</strong>
        Internet Explorer 8 and lower are not supported by this website.
    </div>

Let's start customizing plugins.