HTML – Using ARIA to make our web pages accessible

HTML – Using ARIA to make our web pages accessible

ARIA stands for ‘Accessible Rich Internet Applications’ and can help make your website more accessible to people with disabilities such as hearing or visual impairment.

We have a lot of help from modern HTML that will help set up the semantic meaning of our websites.

Use semantic HTML elements where possible.
The browser has gotten pretty good at applying semantics to pieces of a page when we use the correct elements to lay out our page. Some examples are nav, button, article. They have default aria statements of role="navigation" etc. It used to be pretty common to have elements like <div class="main-navigation" role="navigation">. But, today we can replace the div with a nav and no longer need to specify the role.

There are times that we need to provide more context to what is going on on our page, so we can describe many more things with additional ARIA attributes.


role

Roles describe widgets and structure. They are added as attributes on elements.
Roles are used as navigation aids for assistive software like screen readers.

<div id="header" role="banner">
<div id="nav"  role="navigation">

aria-label and aria-labelledby

The aria-label attribute is used to label a form element that is not visible on the page, maybe this is dictated by design etc, but we still need to provide the screen reader with something to describe the widget.

A button may be styled to look like a close button, with an X in the middle. Since there is nothing indicating that the purpose of the button is to close the dialog, the aria-label attribute is used to provide the label to assistive technologies.


<button aria-label="Close" onclick="myDialog.close()">X</button>

When the text is visible, we should use aria-labelledby instead.

<div id="billing">Billing</div>
  <div>
    <div id="name">Name</div>
    <input type="text" aria-labelledby="billing name"/>
  </div>
  <div>
    <div id="address">Address</div>
    <input type="text" aria-labelledby="billing address"/>
  </div>

aria-disabled

Some aria attributes are used to describe the state of the widget. It is common for aria states to change on a page, whereas properties generally stay static.
aria-disabled="true" helps describe to assistive technology that a widget is present, but it is not currently functional – disabled. Some readers will skip right over disabled content, some will announce that it’s unavailable.


aria-haspopup

The aria-haspopup="true" can be used to describe that there is a menu or sub-menu. You attach it to the element that will trigger the menu.


aria-hidden

The aria-hidden attribute is used to tell the screen readers to ignore the element. This will cover children elements as well. The elements are described as not perceivable to any user.


aria-expanded

The aria-expanded is another aria state that can take true or false saying that an element is currently expanded and visible. False means the expandable section or items are currently collapsed or invisible.


aria-busy

The aria-busy="true" state is used as part of a live region. Setting this to true when a relevant portion of the page is currently getting updated and the users are waiting to get the updated content. Readers will wait until the attribute is removed before it continues providing that information to the user. Sometimes they will hear “busy” audibly while waiting.


aria-*

aria-* is used to describe global aria attributes that can be used on any html element in any role. Some aria attributes are limited to be used in only certain roles.

ARIA roles, states and properties permitted for use in HTML

CSS Variables

CSS Variables

We all know that we’ve had variables in SASS/LESS etc for a long time. But did you know, that we have native CSS variables right in the browser now!? With zero compiling, transforms or transpiling.

CSS variables, like variables in any programming language, allow us to define styles and reference them anywhere else and even modify them with javascript.

CSS Variables are supported by all modern browsers, except IE
MDN is calling them Custom properties (–*)


How to use them

We can define any CSS property in a CSS variable, ie: color, border, size, position. We prefix their name with --. We declare them by adding them to any element, which will scope just like any other CSS property would.


:root {
  --base-color: #ffc600;
  --spacing: 10px;
  --blur: 10px;
} 

Remember, we can place these on any element, to create scoping. If we created these properties inside the class .main-content and tried to use them outside the scope of elements inside of that class, it would not be applied.


We use them by putting them inside of a var().


img {
  padding: var(--spacing);
  background: var(--base-color);
  filter: blur(var(--blur));
}

We can also provide an optional default value to the var() call.


padding: var(--spacing, 5px);

/* or even multiple fallbacks */
color: var(--color-one, --color-two, red);

You can access and modify your CSS variables in Javascript

One of the most powerful gains we get by using native CSS variables, is we can modify them right inside our page with javascript. Your transpiled languages like SASS are only for build time, and once they are set, they are set.


document.documentElement.style.setProperty('--base-color', 'blue');

No more adding-removing classes just to change between different style sets.


No more defining multiple variables for different media queries

…Or any other scoped changes.

So, you want different link styles on your mobile site than you do on your desktop site? And you still want to provide consistency with variables? Easy. We will use native CSS scoping to redefine the value of our variables only for that scope.


body {
  --primary: #7F583F;
  --secondary: #F7EFD2;
}

a {
  color: var(--primary);
  text-decoration-color: var(--secondary);
}

@media screen and (min-width: 768px) {
  body {
    --primary:  #F7EFD2;
    --secondary: #7F583F;
  }
}

Working example

@Wesbos has a great example of this in his FREE #Javascript30 series. I’ve posted it in a codepen here for you to play with

Working Example


Reminder, Pluralsight has many courses on all of this in many different languages and implementations, and they have a FREE Trial!

Start a 10-day free trial at Pluralsight

CSS Selectors

CSS Selectors

In CSS, selectors are patterns used to select the elements that you want to apply the style to.

Class

Usage: .classname will select any element that has class=”classname”


ID

Usage: #myId will select any element that has id=”myId”. There should always only be one element in a document with a given ID.


Attribute

Selects elements based on the value of the given attribute
Usage: [attr] [attr=value]
More Examples:

/* <a> elements with a title attribute */
a[title] {
  color: purple;
}

/* <a> elements with an href matching "https://example.org" */
a[href="https://example.org"] {
  color: green;
}

/* <a> elements with an href containing "example" */
a[href*="example"] {
  font-size: 2em;
}

/* <a> elements with an href ending ".org" */
a[href$=".org"] {
  font-style: italic;
}

[attr]
Represents an element with an attribute name of attr.

[attr=value]
Represents an element with an attribute name of attr whose value is exactly value.

[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.

[attr|=value]
Represents an element with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, – (U+002D). It is often used for language subcode matches.

[attr^=value]
Represents an element with an attribute name of attr whose value is prefixed by value.

[attr$=value]
Represents an element with an attribute name of attr whose value is suffixed by value.

[attr*=value]
Represents an element with an attribute name of attr whose value contains at least one occurrence of value within the string.

[attr operator value i]
Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively


Pseudo-classes

Allows the selection of elements based on state information that is not contained in the document tree.

Examples: :active :disabled :focus :visited


Sibling

Adjacent sibling: The + combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.
Example: h2 + p will match all <p> elements that directly follow an <h2>.

General siblings: The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.
Example: p ~ span will match all <span> elements that follow a <p>.

Child combinator: The > combinator selects nodes that are direct children of the first element.
Example: ul > li will match all <li> elements that are nested directly inside a <ul> element.

Descendant combinator: The     (space) combinator selects nodes that are descendants of the first element.
Example: div span will match all <span> elements that are inside a <div> element.

Strategy Pattern

What is the Strategy Pattern?

Wikipedia describes it as:

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. The strategy pattern:

  • – defines a family of algorithms
  • – encapsulates each algorithm
  • – makes the algorithms interchangeable within that family

The Strategy Pattern allows you to implement algorithms and usages of those algorithms completely separate. This allows you to have very flexible and reusable code, without the client that is using the code to know anything about how it works. The client can choose which version of the algorithm based on the information that it has; maybe the type of data, where the data came from, maybe user interaction. This can be done in a multitude of ways, including delegates, methods, class instances and interfaces – often using reflection to determine usage.


Let’s look at .NET/Linq’s IList.Sort as an example.

 public class Person {
  public string Name { get; set; }
  public int Age { get; set; }

  public override string ToString() {
    return $"{Name}: {Age}";
  }
}

public class Strategy {
  public static readonly ReadOnlyCollection<Person> People = new List<Person>
  {
    new Person { Name = "RJ", Age = 32 },
    new Person { Name = "Ryan", Age = 30 },
    new Person { Name = "Cassie", Age = 28 },
    new Person { Name = "Robert", Age = 57 }
  }.AsReadOnly();

  public void main() {
    var list = People.ToList();
    // Use a built delegate
    list.Sort(CompareByAge);

    // Use explicit lamda expression
    list.Sort((x, y) => x.Age.CompareTo(y.Age));

    // Implemented Single Method Interface
    list.Sort(new AgeComparer());

    foreach (var person in list) {
      Console.WriteLine(person);
    }
  }

  static int CompareByAge(Person left, Person right) {
    return left.Age.CompareTo(right.Age);
  }

  public class AgeComparer : IComparer<Person> {
    public int Compare(Person left, Person right) {
      return left.Age.CompareTo(right.Age);
    }
  }
}

None of the Comparison methods, know about sorting.

The sort method doesn’t know how to compare.

Clean separation of concerns

Adheres to the SOLID principle, enforcing Single Responsibility for more flexible code.

Using the strategy and implementing the strategy are completely separate.

Linq has endless uses of the Strategy pattern.


My company also takes advantage of this pattern for MVC Controller input model validation. This is just a snippet of it, but we plug in FluentValidation which has an AbstractValidator<T> that registers this Strategy to controllers that have an input model of T. This makes it so the controller does not even need to know about any validation at all. You just register how your Strategy should be applied with a marker interface of IValidated, and it does it. Very easy to add rules and sub-rules, and change it whenever you want, without changing your controller code.


public class AttributesInputModel : FormAttributes, IValidated
{
}

public class AttributesInputModelValidator : AbstractValidator<AttributesInputModel>
{
  public AttributesInputModelValidator(IFormAttributesCache cache)
  {
    CascadeMode = CascadeMode.StopOnFirstFailure;

    RuleFor(x => x.EffectiveDateString)
      .NotNull()
      .WithMessage("The effective date must be provided.");

    RuleFor(x => x.EffectiveDateString)
      .SetValidator(new DateValidator("Must provide a valid effective date."));

    RuleFor(x => x.EffectiveDate)
      .Must(x => x.Day == 1)
      .When(x =>
        !string.IsNullOrEmpty(x.EffectiveDateString)
        && DateValidator.IsValid(x.EffectiveDateString))
      .WithMessage("The effective date must be the first of the month.");

    RuleFor(x => x.ExpirationDateString)
      .SetValidator(new DateValidator("Must provide a valid expiration date, when provided."))
      .When(x => !string.IsNullOrEmpty(x.ExpirationDateString));

    RuleFor(x => x.ExpirationDate)
      .Must((model, x) => !x.HasValue || model.EffectiveDate <= x.Value)
      .When(x =>
        !string.IsNullOrEmpty(x.ExpirationDateString)
        && DateValidator.IsValid(x.ExpirationDateString))
      .WithMessage("Effective date must come before the expiration date.");

    RuleFor(x => x.ExpirationDate)
      .Must((model, x) =>
        !x.HasValue
        || x.Value.Day == DateTime.DaysInMonth(x.Value.Year, x.Value.Month))
      .When(x =>
        !string.IsNullOrEmpty(x.ExpirationDateString)
        && DateValidator.IsValid(x.ExpirationDateString))
      .WithMessage("Expiration date must be the last day of the month.");
  }
}

public class DateValidator : PropertyValidator
{
  public DateValidator(string errorMessage)
    : base(errorMessage) {}

  protected override bool IsValid(PropertyValidatorContext context)
  {
    var dateString = (string)context.PropertyValue;
    return IsValid(dateString);
  }

  public static bool IsValid(string dateString)
  {
    DateTime date;
    var result = DateTime.TryParse(dateString, out date);
    return result;
  }
}

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

CSS – Box Model

All HTML elements can be considered as boxes. In CSS, the term “box model” is used when talking about design and layout.

The CSS box model is essentially a box that wraps each HTML element. It consists of the content itself, its margins, borders, and padding.

This image demonstrates the idea of the box model.
CSS Box Model


Content: The actual content of the box. Includes any text, images or other presentational item.

If the box-sizing property is set to content-box (default), the content area’s size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-height properties.


Padding: Clears an area around the content. Padding is transparent.

The thickness of the padding is determined by the padding-top, padding-right, padding-bottom, padding-left, and shorthand padding properties.

Note: When the content area has a background, it extends into the padding.


Border: A border surrounds the padding and content.

By default the border has a size of 0 — making it invisible — but you can set the thickness, style and color of the border to make it appear.

The thickness of the borders are determined by the border-width and shorthand border properties.

border-top, border-right, border-bottom, border-left: Set the thickness, style and color of one side.

border-width, border-style, border-color: Set the thickness, style, or color individually, but for all four sides.

You can also set one of the three properties of a single side of the border individually, using border-top-width, border-top-style, border-top-color, etc.


Margin: Clears another area outside of the border. Margin is also transparent

Used to separate the element from its neighbors. Determined by the margin-top, margin-right, margin-bottom, margin-left, and shorthand margin properties.

Note: Margins have a specific behavior called margin collapsing: When two boxes touch against one another, the distance between them is the value of the largest of the two touching margins, and not their sum.

Note: Vertical margins, top and bottom, are not accepted by inline-level elements.


You can use this model to define space and border around and between different html elements.

div {
  width: 200px;
  margin: 10px;
  padding: 15px;
  border: 2px solid black;
}

Understanding the size of an HTML element

It is important to remember that when you set the height and width properties with css, you are only setting the size of the content.

To calculate the total size of an element, you need at add padding, borders and margins.

If we needed an element to have a total width of 350px, we would use all of these properties.

div {
  width: 320px;
  margin: 0px;
  padding: 10px;
  border: 5px solid black;
}

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

CSS Units of Measure

CSS has several units of measurements to express length.

Many CSS properties take a length. Some of these are: padding, margin, width, font-size, border-width etc.
You declare these properties with a number and then a unit to measure by, ie: 20px.

There are two classes of measurements, Relative and Absolute.

Relative measurement units specify a length relative to another property. Relative measurements scare better in different rendering environments.

Examples of Relative measurements:
em – Relative to the font-size of the existing element. Ie: 2em will make it two times the size of the current font. If the font size is 12px, 2em would be 24px.

p { font-size: 2em; }

rem – Relative to the font-size of the root element. rem is new with CSS3. This allows us to do relative sizing with a set base within a HTML element. 1rem by default is 16px.

The main problem with em units is that they are relative to the font size of their own element. As such they can cascade and cause unexpected results. You have to worry a lot more about nesting when using em. rem gives you a starting point for the entire document without worrying about what else modified your elements along the document tree.

body {  font-size: 14px; }
div { font-size: 1.2em; // calculated at 14px * 1.2, or 16.8px }

<body>
  <div>
    Test <!-- 14 * 1.2 = 16.8px -->
    <div>
      Test <!-- 16.8 * 1.2 = 20.16px -->
      <div>
        Test <!-- 20.16 * 1.2 = 24.192px -->
      </div>
    </div>
  </div>
</body>

Another way to size things relatively is to increase or decrease their size by percentage. A length set in percentage is based on the length of same property of the parent element. For example, if an element renders at 450px width, a child element with a width set to 50% will render at 225px

p { line-height: 120%; }

The most common way to set lengths absolutely is with screen pixels. You can set length properties with the px notation. Pixel size is slightly dependent on the resolution of the device. For screen displays, it traditionally represents one device pixel (dot). However, for printers and high-resolution screens, one CSS pixel implies multiple device pixels, so that the number of pixels per inch stays around 96.

p { width: 400px; }

Command Query Responsibility Segregation

Remember to Start your Free Trial today! for Pluralsight to learn more about all of these topics!

Start a 10-day free trial at Pluralsight

What is CQRS?

The first thing to mention is that CQRS is just a pattern. It is not an architecture or style or framework. It is simply a pattern to follow for scaling large systems. It is built upon the more simple principle of Command Query Separation, “A method should either change the state of an object, or return a result, but not both”

Command Query Separation makes reasoning about objects easier and is broadly applicable.

CQRS is much more specific and not broadly applicable.

The problem that CQRS solves is Blocking the User when Locking the Data

This is commonly seen when you have a large set of people acting on a small set of data.

A good example would be when users would be trying to pick seats for an air plane. Many people may want the same seats. Only one person will end up with the seat and the others will have to try again. This is even worse when someone is trying to reserve seats for a family and wants several seats together. They will become blocked several times before they are able to get seats they may like.

Locking the data is necessary, you must ensure that only one person gets a seat. But, blocking the user in that process is not necessary.

One option would be to introduce a ticketing agent that takes everyone’s requests and assigns the seats and then lets the passengers know of their assignment. The users could then query the status of the seat assignments. But, what they can’t do is change the seating assignments. They can’t affect the seating assignment object directly. For that, they’ll need to go back to the ticket agent. This is not preferred either. There is no immediate feedback.


The first step is to separate out your commands/updates from your queries. You should never return information from a command. If you need to track any kind of status of a transaction, the caller should generate the identifier so that he can call back or query for that status at a later time. Don’t wait for the command to have to fully complete while the user is waiting and blocked.

This improves the situation programmatically by not creating any read locks on data when a user intends to update the same data that is being read by another. It avoids either user from becoming the victim of a deadlock.

It now becomes important to have a queue of messages to process. These can be processed in the order they were received or in a priority and never create any locks. At this point you can have a separate service that queries for the status of that transaction for completion. You can see my post about service bus implementation HERE.

The trade off you are making is Eventual Consistency for Availability. You are making the user experience better and never blocking with the small drawback of potentially stale data.

The CAP Theorem says you can only ever choose 2 of 3 for:

  • Consistency – never receive old data
  • Availability – reasonable response without an error
  • Partition Tolerance – unavoidable because you can’t control the network

Some things you will want to make sure you keep in mind are:

  • Persisting these messages in case of network problems/latency
  • Guarantees of messages being processed
  • Guarantees that messages won’t be duplicated

The next big benefit of CQRS is now that you have your commands separated from your queries, you can have different data models for each side. You don’t need large Data Transfer Objects that know about all the related data, know how to modify it, getters and setters, business logic etc.

Instead, you can have different models for different parts of the system. Depending who is asking for the data and what they need to do with it, they can query in different ways and only for the data that they need (say to display some of the data on a web page), and have their own model to do so. Since they don’t need to keep track of modifying this data, they don’t need all the extra cruft, extra data, all the rules etc. They can just ask for exactly what they want.

The commands can also be cut down in size to know how to modify the part of the data that it cares about.

This allows you to structure your applications in a way that they only care about the parts they are dealing with. You can have more specific commands and queries for specific data, that doesn’t necessarily represent the structure while in the database.

This also allows you to scale your architecture and hardware separately and independently of each other. If you need to support millions of queries, but only a handful of commands, you don’t need to scale them together. You get distinct optimization and huge scalability potential.

Some side effects of implementing this pattern is usually a simplified design, hassle free enhancements, and opens yourself up for some other event based architectures and design patterns.

ES6 Rest/Spread Operator Usage

We all know that the javascript (...) rest/spread operator has made our lives easier with ES6. I wanted to show you how it is used and a couple of ways that you can use it.

Cory House and others have some fantastic courses on @Pluralsight about the great new features of ES6
Start your Free Trial today!

Start a 10-day free trial at Pluralsight

Rest parameters to functions

Functions have the magic arguments variable, but it is not very clean, and it’s not actually an array member. So you can’t use the array functions on it like map, slice etc.


  function concat () {
    return Array.prototype.slice.call(arguments).join(' ')
  }
  var result = concat('this', 'is', 'hard')
  console.log(result)
  // 'this is hard'

Instead, we can provide a named parameter prefixed by ... that will spread the parameters that come in into an array.


  function concat (...words) {
    return words.join(' ')
  }
  var result = concat('this', 'is', 'better')
  console.log(result)
  // 'this is better'

You can also have specific named parameters, followed by an arbitrary number of additional parameters that are spread.


  function multiply(multiplier, ...numbers) {
    return numbers.map(element => {
      return multiplier * element;
    });
  }

  var arr = multiply(2, 1, 2, 3);
  console.log(arr); // [2, 4, 6]

You can break down your arrays or objects into individual properties if the function you’re calling wants individual parameters, without using apply. Or even, mix and match.


  console.log(1, 2, 3); // '1 2 3'

  console.log.apply(console, [1, 2, 3]); // '1 2 3'

  console.log(...[1, 2, 3]); // '1 2 3'

  console.log(1, ...[2, 3, 4], 5) // '1 2 3 4 5'

Another very good bonus is that it can be used on anything that is an iterable. So if you’re working with nodes/dom elements that aren’t arrays, but are still a list of things you want to work with, you can spread them into a real array that you can work with.


  [...document.querySelectorAll('div')]
  // [<div>, <div>, <div>]

Composition and Destructuring of objects

We can easily grab properties from one object and add them to another.


  const one = { a: 1, b: 2 };
  const two = { c: 3, d: 4 };
  const three = { ...one, ...two };

  // three = { a: 1, b: 2, c: 3, d: 4 };

  // Then pull off a specific property
  const { d, ...thing } = three;

  // thing = { a: 1, b: 2, c: 3 };

  // assign that specific value to another variable
  let otherVar;
  const { d: otherVar, ...thing } = three;
  // otherVar = 4

Adding properties with dynamic/unknown property names. Maybe a React reducer handling a dictionary with keys? We can use [] with a string to give a named property key for an object. The spread operator also is convenient in React reducers where you don’t want to mutate the previous state coming in, rather composing a new state based off the old state. ... will create a copy of an old object/array. Be careful, as spreading arrays of objects will still keep a reference, so it isn’t a copy per se.


  // state = { 1: 'hello', 2: 'welcome' }
  // action = { type: 'add', id: 3, payload: 'goodbye' }
  reducer(state, action) {
    switch(action.type) {
      case: 'add':
        return { ...state, [action.id]: action.payload };
        // returns a new object { 1: 'hello', 2: 'welcome', 3: 'goodbye' }
        // All accomplished on one line!
    }
  }

How about pulling a dynamically named property off of an object?


  // state = { 1: 'hello', 2: 'welcome', 3: 'goodbye' }
  // action = { type: 'remove', id: '2' }
  reducer(state, action) {
    switch(action.type) {
      case: 'remove':
        const {[action.id]: _, ...rest } = state;
        return rest;
        // returns a new object { 1: 'hello', 3: 'goodbye' }
        // We assigned the destructured property to a 'throw-away'
        // variable _
        // Unfortunately, we can't just pull off dynamically
        // named properties, yet.
        // We have to assign them to a throw-away
    }
  }