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

Defining the plugin methods

Now that we have our plugin well declared, we must fill the logic for it. We will create methods inside the prototype to create this behavior. We will only show this portion of the plugin code here.

The first method that we will create is init(). We will call it later to start the plugin. Before that, we have a few steps:

  • Initial verifications
  • Assigning the plugin elements and prerequisites
  • Loading the original Bootstrap template
  • Starting the Bootstrap plugin

The initialize method and plugin verifications

Actually, we have only one requirement from the Bootstrap original carousel plugin: the outmost div must have an id. Let's create the init function while making this assertion:

BootstrapCarousel.prototype = {
  init: function () {
    if(!this.$element.attr('id')){
      throw 'You must provide an id for the Bootstrap Carousel element.';
    }

    this.$element.addClass('slide carousel');
  }
};

Therefore, we check if the element has the attribute id using this.$element.attr('id'). If not, we throw an error to the console and the developer will properly fix this issue. Note that we can access the plugin element using this.$element because we made this assignment at the start of the plugin.

In the last line of the function, we added some classes needed for the Bootstrap Carousel, in case we do not have it in the $element such as .slide and .carousel.

Adding the Bootstrap template

To load the Bootstrap Carousel template, let's create another function called load inside the init method to start it:

BootstrapCarousel.prototype = {
  init: function () {
    if(!this.$element.attr('id')){
      throw 'You must provide an id for the Bootstrap Carousel element.';
    }

    this.$slides = this.$element.find('> img');
    this.$element.addClass('slide carousel');
    this.load();
  }

  load: function() {
  },
};

First, we must remove any Carousel elements that could be already present inside our $element. The elements that we must remove are the ones with the .carousel-inner, .carousel-indicators, and .carousel-control classes. Also, we have to load and hide the slide images in the variable this.$slides:

load: function() {
  // removing Carousel elements
  this.$element.find('.carousel-inner, .carousel-indicators, .carousel-control').remove();

  // loading and hiding the slide images
  this.$slides = this.$element.find('> img');
  this.$slides.hide();
},

Next, we must make sure that there are not any other associations of Bootstrap Carousel in our plugin element. Append the following lines in the function:

this.$element.carousel('pause');
this.$element.removeData('bs.carousel');

First, we will pause the Carousel to stop any interaction and after use the function removeData in the bs.carousel, which is the name of the Carousel plugin.

To continue, we must load the Bootstrap Carousel template. Inside the class prototype, we have to create a variable to hold the original template. The variable will have the following format:

template: {
  slide: '…',
  carouselInner: '…',
  carouselItem: '…',
  carouselIndicator: '…',
  carouselIndicatorItem: '…',
  carouselControls: '…',
},

We are not going to place the full code of each template because it is quite extensive, and it would be better to you to check the full code attached with the book and see each template. Although there are no secrets in the templates, they are just a big string with some marked parts that we will replace. The marked parts are defined as a string around curly brackets, for example, {keyName}. When creating the template, we just need to replace these parts of the string by calling .replace(/{keyName}/, 'value').

Each key inside the template correspond to a certain part of the template. Let's explain each one:

  • slide: This is the slide template of the new plugin and it is used to add slides via JavaScript
  • carouselInner: This is the element inside the carousel that is parent for the items
  • carouselItem: This is the item that contains the image and the caption of a slide
  • carouselIndicator: This is the set of bullets at the bottom of the carousel
  • carouselIndicatorItem: This represents each bullet of the indicator
  • carouselControls: This is the controls to switch between left and right the carousel slides

At the end of the load method, add two more lines:

load: function() {
  this.$element.find('.carousel-inner, .carousel-indicators, .carousel-control').remove();
  this.$slides = this.$element.find('> img');
  this.$slides.hide();

  this.$element.carousel('pause');
  this.$element.removeData('bs.carousel');

  this.$element.append(this.createCarousel());
  this.initPlugin();
},

So, we will append in the this.$element the template generated in the function createCarousel. After that, we just need to initialize the Bootstrap original Carousel plugin.

Creating the original template

The original template will be created in the function createCarousel. It is composed of two steps. The steps are as follows:

  • We create the slide deck for the .carousel-inner element
  • Then, we create the indicator and the controls, if needed

Thus, the createCarousel method is composed of the call of these three functions that will append the string template to a variable:

createCarousel: function() {
  var template = '';

  // create slides
  template += this.createSlideDeck();

  // create indicators
  if(this.options.indicators) {
    template += this.createIndicators();
  }

  // create controls
  if(this.options.controls) {
    template += this.createControls();
  }

  return template
},

Note that for the indicator and the controls we made, check before creating the template. We performed a check in the this.options variable to see if the developer passed the argument to add these components or not.

So, we are defining the first two variables of our plugin. They can be passed through data attributes in the element, like data-indicators and data-controls. It defines whether the template will have these elements or not.

The slide deck

The slide deck will be created by the iterating of each this.$slide and loading the image source, the data-title and the data-content in this case. Also, for the first item, we must apply the class .active. The code is as follows:

createSlideDeck: function() {
  var slideTemplate = '',
      slide;

  for (var i = 0; i < this.$slides.length; i++) {
    slide = this.$slides.get(i);

    slideTemplate += this.createSlide(
      i == 0 ? 'active' : '',
      slide.src,
      slide.dataset.title,
      slide.dataset.content
    );
  };

  return this.template.carouselInner.replace(/{innerContent}/, slideTemplate);
},

In each iteration, we are calling another function named createSlide, where we are passing, if the slide is active, the image source, the item title, and the item content. This function will then replace the template using these arguments:

createSlide: function(active, itemImg, itemTitle, itemContent) {
  return this.template.carouselItem
      .replace(/{activeClass}/, active)
      .replace(/{itemImg}/, itemImg)
      .replace(/{itemTitle}/, itemTitle || this.options.defaultTitle)
      .replace(/{itemContent}/, itemContent || this.options.defaultContent);
}

We performed a check for the title and the content. If there is no title or content provided, a default value will be assigned from this.options. Just like the indicators and controls, these options can be passed through data attributes such as data-default-title and data-default-content in the plugin HTML element.

Note

Do not forget that these options can be also provided in the plugin initialization through JavaScript by calling .bCarousel({ defaultTitle: 'default title' }).

The carousel indicators

The function createIndicators is used to create the indicators. In this function, we will perform the same method of the one to create the slide deck. We will create each bullet and then wrap it in the list of .carousel-indicators:

createIndicators: function() {
  var indicatorTemplate = '',
      slide,
      elementId = this.$element.attr('id');

  for (var i = 0; i < this.$slides.length; i++) {
    slide = this.$slides.get(i);

    indicatorTemplate += this.template.carouselIndicatorItem
      .replace(/{elementId}/, elementId)
      .replace(/{slideNumber}/, i)
      .replace(/{activeClass}/, i == 0 ? 'class="active"' : '');
  }

  return this.template.carouselIndicator.replace(/{indicators}/, indicatorTemplate);
},

The only trick here is that each bullet must be enumerated and have a reference to the parent element id. Thus, we made the replacements for each this.$slides and returned the indicator template.

Tip

Why are replacing the key and surrounding with slashes?

Surrounding with slashes on JavaScript performs a regex search on the pattern provided. This can be useful for custom replaces and specific searches.

The carousel controls

The controls create the arrows to switch slides from left to right. They follow the same methodology as the other templates. Just get a template and replace the keys. This method must be implemented like this:

createControls: function() {
  var elementId = this.$element.attr('id');

  return this.template.carouselControls
    .replace(/{elementId}/g, elementId)
    .replace(/{previousIcon}/, this.options.previousIcon)
    .replace(/{previousText}/, this.options.previousText)
    .replace(/{nextIcon}/, this.options.nextIcon)
    .replace(/{nextText}/, this.options.nextText);
},

Note that in the first replacement for the {elementId}, our regex has an append g. The g on the regex is used to replace all occurrences of the following pattern. If we do not use g, JavaScript will only replace the first attempt. In this template we have two {elementId} keys, using which we replace both at once.

We also have some options passed through plugin initialization for the previous and next icon and the text corresponding to that.

Initializing the original plugin

After creating the original template, we must start the original Carousel plugin. We defined a function called initPlugin with the following implementation:

initPlugin: function() {
  this.$element.carousel({
    interval: this.options.interval,
    pause: this.options.pause,
    wrap: this.options.wrap,
    keyboyard: this.options.keyboard
  });
},

It just starts the plugin by calling this.$element.carousel while passing the carousel options on start. The options are loaded just like the others that we presented before. As shown, the options are loaded in the plugin class definition in the following line:

this.options = $.extend({}, BootstrapCarousel.DEFAULTS, options);

If any option is passed, it will override the default options present in BootstrapCarousel.DEFAULTS. We must create like this:

BootstrapCarousel.DEFAULTS = {
  indicators: true,
  controls: true,
  defaultTitle: '',
  defaultContent: '',
  nextIcon: 'glyphicon glyphicon-chevron-right',
  nextText: 'Next',
  previousIcon: 'glyphicon glyphicon-chevron-left',
  previousText: 'Previous',
  interval: 5000,
  pause: 'hover',
  wrap: true,
  keyboard: true,
};

Making the plugin alive

We are one step away from loading the plugin. To do so, create the following code in the HTML:

<div id="carousel-notification" class="bootstrap-carousel" data-indicators="true" data-controls="true">
  <img src="imgs/doge.jpg" data-title="doge" data-content="Hey there!">
  <img src="imgs/laika.jpg" data-title="laika" data-content="Hey ...!">
  <img src="imgs/cat.jpg" data-title="cat">
</div>

In our plugin JavaScript, we have to ignite the prototype by calling the init function like this:

var BootstrapCarousel   = function (element, options) {
  this.$element = $(element);
  this.options = $.extend({}, BootstrapCarousel.DEFAULTS, options);

  this.init();
}

Hooray! Open the HTML file in our browser and see the plugin in action, as shown in the next screenshot. In the DOM, you can how we perfectly mime the Bootstrap Carousel plugin, reducing the declaration in almost 35 lines of code:

Making the plugin alive