loading...

Bootstrap 4 – Writing a custom Bootstrap jQuery plugin

Following the patterns that we have seen in alert.js and carousel.js, we will build our own plugin. Of course, before we start coding, we need to understand what we want to build.

The idea – the A11yHCM plugin

The A11yHCM plugin, depending on your background and experience, may give you a clue about what we want to build. A11y is the accepted shorthand for Accessibility or Web Accessibility. W3C defines web accessibility at https://www.w3.org/WAI/intro/accessibility.php as follows:

“Web accessibility means that people with disabilities can use the web. More specifically, web accessibility means that people with disabilities can perceive, understand, navigate, and interact with the web, and that they can contribute to the web. Web accessibility also benefits others, including older people with changing abilities due to aging.”

HCM is an acronym for an accessibility-related term—High Contrast Mode. HCM, in its simplest form, modifies the colors on a display to help visually impaired users view content.

However, different tools for enabling HCM may render differently, and some web pages may not actually improve the experience of a visually impaired user in HCM. Let’s take a look at a couple of examples of MyPhoto in HCM using two different tools.

First, we will use macOS X El Capitan’s built-in high contrast options, Invert colors and I ncrease contrast:

Figure 6.9: macOS X El Capitan’s built-in Accessibility settings

With the Invert colors and Increase contrast settings enabled, MyPhoto is displayed quite differently:

Figure 6.10: Viewing MyPhoto with the Invert Colors and Increase Contrast Accessibility settings enabled on macOS X El Capitan, with the About navbar link in a focused state

Let’s take a look at another tool—Google Accessibility’s High Contrast Chrome plugin ( https://chrome.google.com/webstore/detail/high-contrast/djcfdncoelnlbldjfhinnjlhdjlikmph?hl=en).

With the High Contrast Chrome plugin installed, a high contrast button is added to Google Chrome:

Figure 6.11: The High Contrast button in Chrome, which appears after installing Google Accessibility’s High Contrast Chrome plugin

Let’ s see how MyPhoto displays with this High Contrast plugin enabled:

Figure 6.12: Viewing MyPhoto using Google’s Accessibility High Contrast Chrome Plugin, with the ‘About’ navbar link in a focused state

The result of using the High Contrast Chrome plugin is similar to OS X’s built-in high contrast options, but there are slight differences. For instance, the background color of our Services section and our special offers alert changes between the different tools.

At least one element of our page is clearly poor when displayed in HCM—the focused state of our navigation links. In HCM, the focused state of our navigation links—in this case, the Welcome link—is practically illegible.

So, what can we do here, without actually changing our default styles? The first thing that comes to mind is to simply check whether the display is in HCM and apply the appropriate styling, either through JavaScript or CSS. Unfortunately, high contrast may be applied in different ways by different tools, different browsers, operating systems, and devices. Programmatically, it may be very difficult, or even impossible, to always recognize when your page is being displayed in HCM.

It’s time for plan B. Rather than figuring out programmatically when a page is being viewed in high contrast, let’s allow the user to simply tell us when they are viewing the page in HCM. Plan B is what our A11yHCM plugin will allow us to do.

The a11yhcm.js file

The first thing we will do is define the API. Before building a plugin, it is wise to figure out how you want developers to interact with it. By doing this, you will be able to understand exactly what you are trying to build before writing a single line of code.

The fundamental functionality of our plugin is to enable a style sheet to be dynamically loaded and removed from a page based on the occurrence of a specific event. So, we need two things:

  • An event to trigger the JS
  • The path to the style sheet that is to be loaded

We can use a data-attribute to act as the trigger, just as we did with the other plugins, and use it to pass the path of a CSS file. We want the data-attribute to be unique to our plugin, so we must use an appropriate data-attribute postfix. Let’s try something like the following:

    <div  data-a11yhcm="path/to/css">High Contrast Mode
    </div>

That’s nice and succinct. There isn’t anything else we need right now, so we will get to writing our JavaScript. Our plugin’s JavaScript code will live in js/a11yhcm.js. Let’s set up our skeleton; just like we saw earlier, we want it immediately invoked and added to our page’s jQuery object. We want to create an on-click listener for any element with the data-a11yhcm attribute, but we need to declare which function it triggers. As we want this plugin to dynamically load and remove a style sheet, we will call our function toggle as it toggles HCM on and off. We also want to add a VERSION constant:

    +function ($) {
        'use strict';
        // A11YHCM CLASS DEFINITION
        // ======================
        var A11yHCM = function (element, options) {
        $(element).on('click', '[data-a11yhcm]', this.toggle)
        }
    A11yHCM.VERSION = '1.0.0'
    }(jQuery);

Next, we want to add the plugin definition. As explained earlier, the plugin definition creates an instance of the plugin for each DOM element with the a11yhcm class. Observe the following code:

    // A11YHCM PLUGIN DEFINITION
    // =======================
    function Plugin(option) {
    return this.each(function () {
        var $this = $(this)
        var data = $this.data('bs.a11yhcm')
        if (!data) $this.data('bs.a11yhcm', (data = new A11yHCM(this)))
        if (typeof option == 'string') data[option].call($this)
        })
    }
    var old = $.fn.a11yhcm
    $.fn.a11yhcm = Plugin
    $.fn.a11yhcm.Constructor = A11yHCM  

We’d better not forget the noConflict function to help resolve namespace collisions:

    // A11YHCM NO CONFLICT
    // =================
    $.fn.a11yhcm.noConflict = function () {
        $.fn.a11yhcm = old
        return this
    }

Now we’re getting to the fun part. Before we get into coding the functionality, we must declare our API. We know we want to use the data-a11yhcm attribute as our trigger (and to pass data to our plugin) and to use the toggle function that we declared in the constructor. Observe the following code:

    // A11YHCM DATA-API
    // ==============
    $(document).on('click.bs.allyhcm.data-api', '[data-a11yhcm]', 
    A11yHCM.prototype.toggle)

We also want to ensure that our plugin definition is called for all elements with the data-a11yhcm attributes. Add this to the data API:

    $(window).on('load', function () {
        $('[data-a11yhcm]').each(function () {
            var $a11yhcm = $(this)
            Plugin.call($a11yhcm, $a11yhcm.data())
        })
    })

Okay, now all we need to do is write the toggle function! Let’s discuss our approach. The first thing we need to do is get the reference to the style sheet to be loaded from the data-a11yhcm attribute. Observe the following code:

    A11yHCM.prototype.toggle = function (e) {
        var $this = $(this)
        var styleSheet = $this.attr('data-a11yhcm')
    }

That’s easy. Then, we need to figure out the current state. Are we in HCM or not? We can separate the functionality into on and off functions, hiding and showing the options in the UI as appropriate, much like our alert, expand, and minimize customizations. However, let’s try to keep the API and DOM manipulation to a minimum. Instead, we can simply check to see whether the link tag with the high contrast style sheet is present in the DOM. To do that, we need a way of being able to select the link tag. We will do this by adding the link tag with a unique ID— bs-a11yhcm. Let’s update toggle with a check to see whether the element exists. If it does, use jQuery to remove it; if it doesn’t, we will use jQuery to append it to the head of the DOM:

    if(document.getElementById('bs-a11yhcm'))
        $('#' + $this.styleSheetID).remove()
    else {
        var styleSheetLink = '<link href="' + styleSheet + '" 
      rel="stylesheet" />'
        $('head').append(styleSheetLink)
    }

That’s pretty much it! Let’s do one more thing. What if, by some chance, there is already another element on the page, unrelated to A11yHCM, with the id value of bs-a11yhcm? Rather than forcing a developer to change their page to suit the plugin, we will do the right thing and allow the developer to pass in a custom value for the id. The toggle function will check to see whether an a11yhcm-id attribute exists; if it does, A11yHCM will use that value as the id for the link tag. In that case, an element using A11yHCM can look like this:

    <div  data-a11yhcm="path/to/css" a11yhcm-
    >High Contrast Mode</div>

Let’s update the toggle function to reflect this. We will add the default value for the id as a property of A11yHCM:

    var A11yHCM = function (element) {
        this.$element = $(element)
    }
    A11yHCM.VERSION = '1.0.0'
    A11yHCM.DEFAULTS = {
        styleSheetID : 'bs-a11yhcm'
    }
    A11yHCM.prototype.toggle = function (e) {
        var $this = $(this)
        var styleSheet = $this.attr('data-a11yhcm')
    if ($this.attr('a11yhcm-id'))
        $this.styleSheetID = $this.attr('a11yhcm-id')
      else
        $this.styleSheetID = A11yHCM.DEFAULTS.styleSheetID
      if (document.getElementById($this.styleSheetID))
        $('#' + $this.styleSheetID).remove()
    else {
       var styleSheetLink = '<link href="' + styleSheet + '"
       rel="stylesheet" />'
       $('head').append(styleSheetLink)
    }
}

Okay, that’s it. That looks like all the JavaScript we’ll need to make A11yHCM work the way we envisaged. Now, let’s put it into practice by adding the markup.

The markup

The first thing we have to do is ensure that the JavaScript for the A11yHCM plugin is loaded. Include the JS file in the head of the page, after bootstrap.min.js and jquery.min.js. Observe the following code:

    <script src="js/alert.js"></script>
    <script src="js/carousel.js"></script>
    <script src="js/a11yhcm.js"></script>

Let’s add the new High Contrast Mode option to the Profile drop-down. We will also include a contrast icon from Font Awesome, and we want to load styles/myphoto-hcm.css:

    <ul class="navbar-nav pull-right">
   <li class="nav-item dropdown ">
      <a href="#" class="nav-link dropdown-toggle" data-toggle= 
         "dropdown" role="button"
         aria-haspopup="true" aria-expanded="false"> Profile <span 
         class="caret"></span>
      </a>
      <div class="dropdown-menu dropdown-menu-right">
         <a class="dropdown-item" href="#" data-toggle="modal" data-
            target="#profile-modal">
         <i class="fa fa-user"></i> Profile
         </a>
         <a class="dropdown-item" href="#" data-toggle="modal" data-
            target= "#settings-modal">
         <i class="fa fa-cogs"></i> Settings
         </a>
         <a class="dropdown-item a11yhcm" href="#" data-
            a11yhcm="styles/myphoto-hcm.css">
         <i class="fa fa-adjust"></i> High Contrast Mode
         </a> 
         <div class="dropdown-divider"></div>
         <a class="dropdown-item" href="#"><i ></i> Logout</a>
      </div>
   </li>
</ul>

Take a look at the screenshot in figure 6.13 to see the menu in action:

Figure 6.13: The new High Contrast Mode menu item

Great. Now, of course, when we click on High Contrast Mode, we won’t able to see any visual changes as we haven’t actually created styles/myphoto-hcm.css. However, if we inspect the DOM, we should be able to see the CSS file referenced in the head. Take a look at the following screenshot:

Figure 6.14: The High Contrast Mode style sheet dynamically added by the High Contrast Mode button

Click on the High Contrast Mode button again, and the link element should be removed. Take a look at the following screenshot:

Figure 6.15: The High Contrast Mode style sheet dynamically removed by the High Contrast Mode button

That’s great, our plugin is working. Let’s pass in a non-default value to be used as the ID for the link element to ensure that that’s also working as expected:

    <a href="#"  data-
    a11yhcm="styles/myphoto-hcm.css" a11yhcm->

Take a look at the following screenshot:

Figure 6.16: The High Contrast Mode style sheet dynamically added by the High Contrast Mode button with a custom ID attribute

That’s perfect. All functionality is working just like we wanted. Now, let’s get to the CSS!

Adding some style

First, we’ll write the style sheet for A11yHCM, and for good measure, we will write myphoto-hcm.css to make our navigation more useful in High Contrast Mode.

Create a styles/a11yhcm.css file and include it in the head of our page:

    <link rel="stylesheet" href="node_modules/font-
    awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" href="styles/alert.css" />
    <link rel="stylesheet" href="styles/carousel.css" />
    <link rel="stylesheet" href="styles/a11yhcm.css" />

All we will do here is toggle the a11yHCM element to indicate whether it is disabled or enabled. We’ll simply add a check mark when it is enabled. We will need a little bit of JavaScript too, to add and remove the enabled class to our element. First, let’s write the CSS:

.a11yhcm.enabled:after {
    content: '\2713';
}

This rule simply appends a check mark to the end of any content within an element with both the a11yhcm and enabled class applied, using the after pseudo-class. Let’s update a 11yHCM.js to add and remove the enabled class:

    if (document.getElementById($this.styleSheetID)) {
        $('#' + $this.styleSheetID).remove()
        $this.removeClass('enabled')
    }
    else {
        var styleSheetLink = '<link href="' + styleSheet + '" 
        rel="stylesheet" />'
        $('head').append(styleSheetLink)
        $this.addClass('enabled')
    }

Our entire toggle function should now look as follows:

A11yHCM.prototype.toggle = function (e) {
 var $this = $(this)
 var styleSheet = $this.attr('data-a11yhcm')
 if($this.attr('a11yhcm-id'))
     $this.styleSheetID = $this.attr('a11yhcm-id')
 else
     $this.styleSheetID = A11yHCM.DEFAULTS.styleSheetID
     if(document.getElementById($this.styleSheetID)) {
     $('#' + $this.styleSheetID).remove()
     $this.removeClass('enabled')
 } else {
     var styleSheetLink = '<link href="' + styleSheet + '" 
     rel="stylesheet" />'
     $('head').append(styleSheetLink)
     $this.addClass('enabled')
 }
}

Let’s check it out. Click on the High Contrast Mode button:

Figure 6.17: The check mark is applied to the menu item to indicate when High Contrast Mode is enabled

That’s great. We now have a visual indicator for when High Contrast Mode is enabled. The check mark might not be suitable for every design, but the rules can always be extended!

Now, let’s get to fixing our navigation.

Create styles/myphotohcm.css and copy over the classes related to the hover, focus, and active states of the navigation from myphoto.css:

    .navbar-myphoto .navbar-nav > li > a:hover {
        background-color: #504747;
        color: gray;
    }
    .navbar-myphoto .navbar-nav > li > a:focus {
        background-color: #504747;
        color: gray;
    }
    .navbar-myphoto .navbar-nav > li.active > a {
        background-color: #504747;
        color: gray;
    }
    .navbar-myphoto .dropdown-menu > a {
        color: white;
        background-color: #504747;
    }
    .navbar-myphoto .dropdown-menu > a:hover {
        color: gray;
        background-color: #504747;
    }
    .navbar-myphoto .dropdown-menu > a:focus {
        color: gray;
        background-color: #504747;
    }
    .navbar-myphoto .dropdown-menu > .active > a:focus {
        color: gray;
        background-color: #504747;
    }

We want these states to be very clear in High Contrast Mode. For full effect, we will use the color blue, but hang on before you go changing all the color properties to blue. The high contrast tools we’re using are inverting the colors, so we need the inverse of blue, that is, yellow. Observe the following code:

 .navbar-myphoto .nav-item>.active {
  color: yellow !important;
}
.navbar-myphoto .nav-item>.nav-link:hover,
.navbar-myphoto .nav-pills>li.active>a,
.navbar-myphoto .dropdown-menu>a:hover,
.navbar-myphoto .dropdown-menu>a:focus {
  color: yellow;
}

Enable high contrast on your browser or OS, and then click on  High Contrast Mode on the MyPhoto page to see the results. Take a look at the following screenshot:

Figure 6.18: Viewing MyPhoto using Google’s Accessibility High Contrast Chrome Plugin, with the “About” navbar link in a focused state and with MyPhoto’s High Contrast Mode enabled (example04.html)

The UI is now much clearer and all thanks to our custom-built A11yHCM jQuery plugin. There is a lot more to do to make this page fully accessible, but it’s a start.

Comments are closed.

loading...