ng

Filamentous and step-like behavior of gelling coarse fibrin networks revealed by high-frequency microrheology

Soft Matter, 2020, 16,4234-4242
DOI: 10.1039/C9SM02228G, Paper
Pablo Domínguez-García, Giovanni Dietler, László Forró, Sylvia Jeney
By a micro-experimental methodology, we study the ongoing molecular process inside coarse fibrin networks by means of microrheology.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Rapid analysis of cell-generated forces within a multicellular aggregate using microsphere-based traction force microscopy

Soft Matter, 2020, 16,4192-4199
DOI: 10.1039/C9SM02377A, Paper
Buğra Kaytanlı, Aimal H. Khankhel, Noy Cohen, Megan T. Valentine
We measure cell-generated forces from the deformations of elastic microspheres embedded within multicellular aggregates. Using a computationally efficient analytical model, we directly obtain the full 3D mapping of surface stresses within minutes.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Systematic approach for wettability prediction using molecular dynamics simulations

Soft Matter, 2020, 16,4299-4310
DOI: 10.1039/D0SM00197J, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Ahmed Jarray, Herman Wijshoff, Jurriaan A. Luiken, Wouter K. den Otter
An efficient approach for fast screening of liquids in terms of their wetting properties.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Structural characterization of fibrous synthetic hydrogels using fluorescence microscopy

Soft Matter, 2020, 16,4210-4219
DOI: 10.1039/C9SM01828J, Paper
Open Access
Johannes Vandaele, Boris Louis, Kaizheng Liu, Rafael Camacho, Paul H. J. Kouwer, Susana Rocha
The structural features of the matrix surrounding the cells play a crucial role in regulating their behavior.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Vesicle adhesion in the electrostatic strong-coupling regime studied by time-resolved small-angle X-ray scattering

Soft Matter, 2020, 16,4142-4154
DOI: 10.1039/D0SM00259C, Paper
Open Access
Karlo Komorowski, Jannis Schaeper, Michael Sztucki, Lewis Sharpnack, Gerrit Brehm, Sarah Köster, Tim Salditt
We have used time-resolved small-angle X-ray scattering (SAXS) to study the adhesion of lipid vesicles in the electrostatic strong-coupling regime induced by divalent ions.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Harnessing biomimetic cryptic bonds to form self-reinforcing gels

Soft Matter, 2020, Advance Article
DOI: 10.1039/D0SM00145G, Paper
Santidan Biswas, Victor V. Yashin, Anna C. Balazs
Cryptic sites, which lay hidden in folded biomolecules, become exposed by applied force and form new bonds that reinforce the biomaterial.
To cite this article before page numbers are assigned, use the DOI form of citation above.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Sustainable sorbitol-derived compounds for gelation of the full range of ethanol–water mixtures

Soft Matter, 2020, Advance Article
DOI: 10.1039/D0SM00343C, Paper
Glenieliz C. Dizon, George Atkinson, Stephen P. Argent, Lea T. Santu, David B. Amabilino
A combination of gelators prepared from sustainable sources combine in a synergic way to widen the scope for the compounds to immobilise liquids, as shown by imaging, diffraction and rheology measurements.
To cite this article before page numbers are assigned, use the DOI form of citation above.
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Simulations of Interpenetrating Networks Microgel Synthesis

Soft Matter, 2020, Accepted Manuscript
DOI: 10.1039/D0SM00287A, Paper
Vladimir Yurievich Rudyak, Elena Kozhunova, Alexander V. Chertovich
In this paper we implement the sequential template synthesis of the interpenetrating network (IPN) microgels in computer simulations and study the behavior of such particles. We explore the influence of...
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Investigation of Thermal Conductivity for Liquid Metal Composites Using Micromechanics-Based Mean-Field Homogenization Theory

Soft Matter, 2020, Accepted Manuscript
DOI: 10.1039/D0SM00279H, Paper
JiYoung Jung, Seunghee Jeong, Klas Hjort, Seunghwa Ryu
For the facile use of liquid metal composite (LMC) for soft, stretchable and thermal systems, it is crucial to understand and predict the thermal conductivity of the composite as a...
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Single chain in mean field simulation of flexible and semiflexible polymers: Comparison with discrete chain self-consistent field theory

Soft Matter, 2020, Accepted Manuscript
DOI: 10.1039/D0SM00620C, Paper
So Jung Park, Jaeup Kim
Single chain in mean field (SCMF) simulation is a theoretical framework performing Monte Carlo moves of explicit polymer chains under quasi-instantaneously updated external fields which were originally imported from the...
The content of this RSS Feed (c) The Royal Society of Chemistry




ng

Designing a World-Class Architecture Firm: The People, Stories, and Strategies Behind HOK


 

Offers architects and creative services professionals exclusive insights and strategies for success from the former CEO of HOK.

Designing a World Class Architecture Firm: The People, Stories and Strategies Behind HOK tells the history of one of the largest design firms in the world and draws lessons from it that can help other architects, interior designers, urban planners and creative services professionals grow bigger or better. Former HOK CEO Patrick



Read More...




ng

Understanding and increasing digital readiness


The Cisco Digital Readiness Index was developed to holistically measure a countryâ€TMs level of digital readiness.
More RSS Feed for Cisco: newsroom.cisco.com/rss-feeds ...




ng

Here's how business needs to change for a new decade


Running a good business carries a responsibility to think about the communities in which they operate.
More RSS Feed for Cisco: newsroom.cisco.com/rss-feeds ...




ng

Participating in the internet for the future


The three pillars of Ciscoâ€TMs “Internet for the Future†strategy are its investments in silicon, optics, and software.
More RSS Feed for Cisco: newsroom.cisco. ...






ng

Securing IoT for your Competitive Advantage


Delivering visibility, analytics, automation, and security across the branch, campus, and data center into operational environments.
More RSS Feed for Cisco: newsroom.cisco.com/rss-feeds ...




ng

Coronavirus | Chennai-based ayurvedic pharmacist dies after drinking concoction of his own preparation

Managing Director of the firm faints after tasting the chemical




ng

Tapping expertise — how T.N. is handling the crisis

Multiple panels with senior bureaucrats constituted to address issues arising out of the pandemic




ng

T.N. to order 10 lakh more RT-PCR testing kits

Tamil Nadu is ordering 10 lakh more RT-PCR (reverse transcription-polymerase chain reaction) testing kits to ramp up testing across the State.Accordin




ng

HC seeks report on testing

The Madras High Court on Friday granted time till Monday for the State government to file a comprehensive report on steps taken to conduct mass testin




ng

Cine industry welcomes govt.’s decision allowing post-production work

The announcement by the Tamil Nadu government allowing post-production work on films and television projects to resume from May 11 was welcomed by the




ng

Ranipet police foil protest move against opening of Tasmac shop

Police personnel and staff of the Tamil Nadu State Marketing Corporation Limited foiled a protest attempt against the opening of a liquor shop at Rani




ng

HC warns State of being imposed with costs

The Madras High Court on Friday warned the State government of being imposed with costs if it fails to file a counter affidavit by Tuesday to a public




ng

Inspect chemical factories before reopening: Tamil Nadu Consumer Protection Organisation

The Tamil Nadu Consumer Protection Organisation has asked the Tamil Nadu government to form a committee of officials from the environment, industries




ng

Explain methodology for issuing e-passes: HC

The Madras High Court on Friday called for a report from the State government explaining the methodology adopted by it for issuing e-passes for the tr




ng

[ASAP] Low-Threshold Lasing up to 360 K in All-Dielectric Subwavelength-Nanowire Nanocavities

ACS Photonics
DOI: 10.1021/acsphotonics.0c00166




ng

[ASAP] Monochromatic X-ray Source Based on Scattering from a Magnetic Nanoundulator

ACS Photonics
DOI: 10.1021/acsphotonics.0c00121




ng

[ASAP] Describing Meta-Atoms Using the Exact Higher-Order Polarizability Tensors

ACS Photonics
DOI: 10.1021/acsphotonics.9b01776




ng

[ASAP] Plasmon-Mediated Coherent Superposition of Discrete Excitons under Strong Exciton–Plasmon Coupling in Few-Layer MoS<sub>2</sub> at Room Temperature

ACS Photonics
DOI: 10.1021/acsphotonics.0c00233




ng

[ASAP] Room Temperature Graphene Mid-Infrared Bolometer with a Broad Operational Wavelength Range

ACS Photonics
DOI: 10.1021/acsphotonics.0c00028




ng

[ASAP] Size, Ligand, and Defect-Dependent Electron–Phonon Coupling in Chalcogenide and Perovskite Nanocrystals and Its Impact on Luminescence Line Widths

ACS Photonics
DOI: 10.1021/acsphotonics.0c00034




ng

[ASAP] Development of Lipid-Coated Semiconductor Nanosensors for Recording of Membrane Potential in Neurons

ACS Photonics
DOI: 10.1021/acsphotonics.9b01558




ng

[ASAP] Ultrafast Dynamics of Optically Induced Heat Gratings in Metals

ACS Photonics
DOI: 10.1021/acsphotonics.0c00224




ng

[ASAP] Large Wavelength Response to Pressure Enabled in InGaN/GaN Microcrystal LEDs with 3D Architectures

ACS Photonics
DOI: 10.1021/acsphotonics.0c00251




ng

[ASAP] Quasinormal-Mode Non-Hermitian Modeling and Design in Nonlinear Nano-Optics

ACS Photonics
DOI: 10.1021/acsphotonics.0c00014




ng

[ASAP] Directional off-Normal Photon Streaming from Hybrid Plasmon-Emitter Coupled Metasurfaces

ACS Photonics
DOI: 10.1021/acsphotonics.0c00196




ng

[ASAP] Chip-Scale Reconfigurable Optical Full-Field Manipulation: Enabling a Compact Grooming Photonic Signal Processor

ACS Photonics
DOI: 10.1021/acsphotonics.0c00103




ng

[ASAP] Colored Radiative Cooling Coatings with Nanoparticles

ACS Photonics
DOI: 10.1021/acsphotonics.0c00513




ng

[ASAP] Gain-Assisted Optomechanical Position Locking of Metal/Dielectric Nanoshells in Optical Potentials

ACS Photonics
DOI: 10.1021/acsphotonics.0c00213




ng

[ASAP] Probing the Radiative Electromagnetic Local Density of States in Nanostructures with a Scanning Tunneling Microscope

ACS Photonics
DOI: 10.1021/acsphotonics.0c00264




ng

[ASAP] Line-Scan Hyperspectral Imaging Microscopy with Linear Unmixing for Automated Two-Dimensional Crystals Identification

ACS Photonics
DOI: 10.1021/acsphotonics.0c00050




ng

[ASAP] Strong Optical Feedback Stabilized Quantum Cascade Laser

ACS Photonics
DOI: 10.1021/acsphotonics.0c00189




ng

Making a Better Custom Select Element

Julie Grundy kicks off this, our fifteenth year, by diving headlong into the snowy issue of customising form inputs. Nothing makes a more special gift at Christmas that something you’ve designed and customised yourself. But can it be done while staying accessible to every user?


In my work as an accessibility consultant, there are some frequent problems I find on people’s websites. One that’s come up a lot recently is that people are making custom select inputs for their forms. I can tell that people are trying to make them accessible, because they’ve added ARIA attributes or visually-hidden instructions for screen reader users. Sometimes they use a plugin which claims to be accessible. And this is great, I love that folks want to do the right thing! But so far I’ve never come across a custom select input which actually meets all of the WCAG AA criteria.

Often I recommend to people that they use the native HTML select element instead. Yes, they’re super ugly, but as Scott Jehl shows us in his article Styling a Select Like It’s 2019 they are a lot easier to style than they used to be. They come with a lot of accessibility for free – they’re recognised and announced clearly by all screen reader software, they work reliably and predictably with keyboards and touch, and they look good in high contrast themes.

But sometimes, I can’t recommend the select input as a replacement. We want a way for someone to choose an item from a list of options, but it’s more complicated than just that. We want autocomplete options. We want to put images in there, not just text. The optgroup element is ugly, hard to style, and not announced by screen readers. The focus styles are low contrast. I had high hopes for the datalist element, but although it works well with screen readers, it’s no good for people with low vision who zoom or use high contrast themes.

Figure 1: a datalist zoomed in by 300%

Select inputs are limited in a lot of ways. They’re frustrating to work with when you have something which looks almost like what you want, but is too restricted to be useful. We know we can do better, so we make our own.

Let’s work out how to do that while keeping all the accessibility features of the original.

Semantic HTML

We’ll start with a solid, semantic HTML base. A select input is essentially a text input which restricts the possible answers, so let’s make a standard input.

<label for="custom-select">User Type</label>
<input type="text" id="custom-select">

Then we need to show everyone who can see that there are options available, so let’s add an image with an arrow, like the native element.

<label for="custom-select">User Type</label>
<input type="text" id="custom-select">
<img src="arrow-down.svg" alt="">

For this input, we’re going to use ARIA attributes to represent the information in the icon, so we’ll give it an empty alt attribute so screen readers don’t announce its filename.

Finally, we want a list of options. An unordered list element is a sensible choice here. It also lets screen reader software understand that these bits of text are related to each other as part of a group.

<ul class="custom-select-options">
  <li>User</li>
  <li>Author</li>
  <li>Editor</li>
  <li>Manager</li>
  <li>Administrator</li>
</ul>

You can dynamically add or remove options from this list whenever you need to. And, unlike our <option> element inside a <select>, we can add whatever we like inside the list item. So if you need images to distinguish between lots of very similar-named objects, or to add supplementary details, you can go right ahead. I’m going to add some extra text to mine, to help explain the differences between the choices.

This is a good base to begin with. But it looks nothing like a select input! We want to make sure our sighted users get something they’re familiar with and know how to use already.

Styling with CSS

I’ll add some basic styles similar to what’s in Scott Jehl’s article above.

We also need to make sure that people who customise their colours in high contrast modes can still tell what they’re looking at. After checking it in the default Windows high contrast theme, I’ve decided to add a left-hand border to the focus and hover styles, to make sure it’s clear which item is about to be chosen.

This would be a good time to add any dark-mode styles if that’s your jam. People who get migraines from bright screens will thank you!

JavaScript for behaviour

Of course, our custom select doesn’t actually do anything yet. We have a few tasks for it: to toggle the options list open and closed when we click the input, to filter the options when people type in the input, and for selecting an option to add it to the input and close the list. I’m going to tackle toggling first because it’s the easiest.

Toggling

Sometimes folks use opacity or height to hide content on screen, but that’s like using Harry Potter’s invisibility cloak. No-one can see what’s under there, but Harry doesn’t cease to exist and you can still poke him with a wand. In our case, screen reader and keyboard users can still reach an invisible list.

Instead of making the content see-through or smaller, I’m going to use display: none to hide the list. display: none removes the content from the accessibility tree, so it can’t be accessed by any user, not just people who can see. I always have a pair of utility classes for hiding things, as follows:

.hidden-all {
  display: none;
}

.hidden-visually {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    overflow: hidden;
    clip: rect(0,0,0,0);
    white-space: nowrap;
    -webkit-clip-path: inset(50%);
    clip-path: inset(50%);
    border: 0;
} 

So now I can just toggle the CSS class .hidden-all on my list whenever I like.

Browsing the options

Opening up our list works well for our mouse and touch-screen users. Our styles give a nice big tap target for touch, and mouse users can click wherever they like.

We need to make sure our keyboard users are taken care of though. Some of our sighted users will be relying on the keyboard if they have mobility or dexterity issues. Usually our screen reader users are in Browse mode, which lets them click the arrow keys to navigate through content. However, custom selects are usually inside form elements. which pushes screen reader software to Forms Mode. In Forms mode, the screen reader software can only reach focusable items when the user clicks the Tab key, unless we provide an alternative. Our list items are not focusable by default, so let’s work on that alternative.

To do this, I’m adding a tabindex of -1 to each list item. This way I can send focus to them with JavaScript, but they won’t be part of the normal keyboard focus path of the page.

csOptions.forEach(function(option) {
    option.setAttribute('tabindex, '-1')
}) 

Now I can move the focus using the Up and Down arrow keys, as well as with a mouse or tapping the screen. The activeElement property of the document is a way of finding where the keyboard focus is at the moment. I can use that to loop through the elements in the list and move the focus point forward or back, depending on which key is pressed.

function doKeyAction(whichKey) {
  const focusPoint = document.activeElement
  switch(whichKey) {
    case: 'ArrowDown':
      toggleList('Open')
      moveFocus(focusPoint, 'forward')
      break
    case: 'ArrowUp':
      toggleList('Open')
      moveFocus(focusPoint, 'back')
      break
  }
}

Selecting

The Enter key is traditional for activating an element, and we want to match the original select input.

We add another case to the keypress detector…

case 'Enter':
  makeChoice(focusPoint)
  toggleList('Shut')
  setState('closed')
  break 

… then make a function which grabs the currently focused item and puts it in our text input. Then we can close the list and move focus up to the input as well.

function makeChoice(whichOption) {
    const optionText = whichOption.documentQuerySelector('strong')
    csInput.value = optionText
}

Filtering

Standard select inputs have keyboard shortcuts – typing a letter will send focus to the first item in the option which begins with that letter. If you type the letter again, focus will move to the next option beginning with that letter.

This is useful, but there’s no clue to tell users how many options might be in this category, so they have to experiment to find out. We can make an improvement for our users by filtering to just the set of options which matches that letter or sequence of letters. Then sighted users can see exactly how many options they’ve got, and continue filtering by typing more if they like. (Our screen reader users can’t see the remaining options while they’re typing, but don’t worry – we’ll have a solution for them in the next section).

I’m going to use the .filter method to make a new array which only has the items which match the text value of the input. There are different ways you could do this part – my goal was to avoid having to use regex, but you should choose whatever method works best for your content.

function doFilter() {
  const terms = csInput.value
  const aFilteredOptions = aOptions.filter(option => {
    if (option.innerText.toUpperCase().startsWith(terms.toUpperCase())) {
    return true
    }
  })
  // hide all options
  csOptions.forEach(option => option.style.display = "none")
  // re-show the options which match our terms
  aFilteredOptions.forEach(function(option) {
    option.style.display = ""
  })
} 

Nice! This is now looking and behaving really well. We’ve got one more problem though – for a screen reader user, this is a jumble of information. What’s being reported to the browser’s accessibility API is that there’s an input followed by some clickable text. Are they related? Who knows! What happens if we start typing, or click one of the clicky text things? It’s a mystery when you can’t see what’s happening. But we can fix that.

ARIA

ARIA attributes don’t provide much in the way of additional features. Adding an aria-expanded='true' attribute doesn’t actually make anything expand. What ARIA does is provide information about what’s happening to the accessibility API, which can then pass it on to any assistive technology which asks for it.

The WCAG requirements tell us that when we’re making custom elements, we need to make sure that as a whole, the widget tells us its name, its role, and its current value. Both Chrome and Firefox reveal the accessibility tree in their dev tools, so you can check how any of your widgets will be reported.

We already have a name for our input – it comes from the label we associated to the text input right at the start. We don’t need to name every other part of the field, as that makes it seem like more than one input is present. We also don’t need to add a value, because when we select an item from the list, it’s added to the text input and therefore is exposed to the API.

Figure 2: How Firefox reports our custom select to assistive technology.

But our screen readers are going to announce this custom select widget as a text entry field, with some images and a list nearby.

The ARIA Authoring Practices site has a pattern for comboboxes with listboxes attached. It tells you all the ARIA you need to make screen reader software give a useful description of our custom widget.

I’m going to add all this ARIA via JavaScript, instead of putting it in the HTML. If my JavaScript doesn’t work for any reason, the input can still be a plain text field, and we don’t want screen readers to announce it as anything fancier than that.

csSelector.setAttribute('role', 'combobox') 
csSelector.setAttribute('aria-haspopup', 'listbox')
csSelector.setAttribute('aria-owns', '#list') 
csInput.setAttribute('aria-autocomplete', 'both')
csInput.setAttribute('aria-controls', 'list')

The next thing to do is let blind users know if the list is opened or closed. For that task I’m going to add an aria-expanded attribute to the group, and update it from false to true whenever the list changes state in our toggling function.

The final touch is to add a secret status message to the widget. We can use it to update the number of options available after we’ve filtered them by typing into the input. When there are a lot of options to choose from, this helps people who can’t see the list reducing know if they’re on the right track or not.

To do that we first have to give the status message a home in our HTML.

<div id='custom-select-status' class='hidden-visually' aria-live='polite'></div>

I’m using our visually-hidden style so that only screen readers will find it. I’m using aria-live so that it will be announced as often as it updates, not just when a screen reader user navigates past it. Live regions need to be present at page load, but we won’t have anything to say about the custom select then so we can leave it empty for now.

Next we add one line to our filtering function, to find the length of our current list.

updateStatus(aFilteredOptions.length)

Then we send that to a function which will update our live region.

function updateStatus(howMany) {
    console.log('updating status')
    csStatus.textContent = howMany + " options available."
}

Conclusion

Let’s review what we’ve done to make an awesome custom select input:

  • Used semantic HTML so that it’s easily interpreted by assistive technology while expanding the types of content we can include in it
  • Added CSS styles which are robust enough to survive different visual environments while also fitting into our branding needs
  • Used JavaScript to provide the basic functionality that the native element has
  • Added more JavaScript to get useful functionality that the native element lacks
  • Carefully added ARIA attributes to make sure that the purpose and results of using the element are available to assistive technology and are updated as the user interacts with it.

You can check out my custom select pattern on GitHub – I’ll be making additions as I test it on more assistive technology, and I welcome suggestions for improvements.

The ARIA pattern linked above has a variety of examples and customisations. I hope stepping through this example shows you why each of the requirements exists, and how you can make them fit your own needs.

I think the volume of custom select inputs out there shows the ways in which the native select input is insufficient for modern websites. You’ll be pleased to know that Greg Whitworth and Simon Pieters are working on improving several input types! You can let them know what features you’d like selects to have. But until that work pays off, let’s make our custom selects as accessible and robust as they can possibly be.


About the author

Julie Grundy is an accessibility expert who works for Intopia, a digital accessibility consultancy. She has over 15 years experience as a front-end web developer in the health and education sectors. She believes in the democratic web and aims to unlock digital worlds for as many people as possible. In her spare time, she knits very slowly and chases very quickly after her two whippets.

More articles by Julie




ng

Twelve Days of Front End Testing

Amy Kapernick sings us through numerous ways of improving the robustness and reliability of our front end code with a comprehensive rundown of ideas, tools, and resources. The girls and boys won’t get any toys until all the tests are passing.


Anyone who’s spoken to me at some point in November may get the impression that I’m a bit of a grinch. But don’t get me wrong, I love Christmas, I love decorating my tree, singing carols, and doing Christmas cooking - in December. So for me to willingly be humming the 12 days of Christmas in October, it’s probably for something that I think is even more important than banning premature Christmas decorations, like front end testing.

On the 12th day of Christmas, my front end dev, she gave to me, 12 testing tools, 11 optimised images, 10 linting rules, 9 semantic headings, 8 types of colour blindness, 7(.0) contrast ratio, 6 front end tests, 5 browser types, 4 types of tests, 3 shaken trees, 2 image types, and a source controlled deployment pipeline.

Twelve Testing Tools

  1. axe does automated accessibility testing. Run as part of your development build, it outputs warnings to your console to let you know what changes you need to make (referencing accessibility guides). You can also specify particular accessibility standard levels that you’d like to test against, eg. best-practice, wcag2a or wcag2aa, or you can pick and choose individual rules that you want to check for (full list of rules you can test with axe).
    aXe Core can be used to automate accessibility testing, and has a range of extensions for different programming languages and frameworks.
  2. BackstopJS runs visual regression tests on your website. Run separately, or as part of your deployment/PR process, you can use it to make sure your code changes aren’t bleeding into other areas of the website. By default, BackstopJS will set you up with a bunch of configuration options by running backstop init in your project to help get you started.
    BackstopJS compares screenshots of your website to previous screenshots and compares the visual differences to see what’s changed.
  3. Website Speed Test analyses the performance of your website specifically with respect to images, and the potential size savings if they were optimised.
  4. Calibre runs several different types of tests by leveraging Lighthouse. You can run it over your live website through their web app or through the command line, it then monitors your website for performance and accessibility over time, providing metrics and notifications of any changes.
    Calibre provides an easy to use interface and dashboard to test and monitor your website for performance, accessibility and several other areas.
  5. Cypress is for end-to-end testing of your website. When visual regression testing may be a bit much for you, Cypress can help you test and make sure elements are still on the page and visible (even if they’re not pixel for pixel where they were last time).
  6. pa11y is for automated accessibility testing. Run as part of your build process or using their CLI or dashboard, it tests your website against various Web Content Accessibility Guidelines (WCAG) criteria (including visual tests like colour contrast). While axe is run as part of your dev build and gives you an output to the console, it can be combined with pa11y to automate any changes as part of your build process.
  7. whocanuse was created by Corey Ginnivan, and it allows you to view colour combinations as those with colour blindness would (as well as testing other visual deficiencies, and situational vision events), and test the colour contrast ratio based on those colours.
    Colour contrast assessment of my brand colours, testing them for issues for people with various vision deficiencies, and situational vision events.
  8. Colour Blindness Emulation was created by Kyo Nagashima as an SVG filter to emulate the different types of colour blindness, or if you’re using Gatsby, you can use a plugin based off of gatsby-plugin-colorblind-filters.
  9. Accessible Brand Colors tests all your branding colours against each other (this is great to show designers what combinations they can safely use).
    Accessible Brand Colors tests all colour combinations of background and text colours available from your branding colours, and checks them for compliance levels at various font sizes and weights.
  10. Browser dev tools - Most of the modern browsers have been working hard on the features available in their dev tools:
    • Firefox: Accessibility Inspector, Contrast Ratio testing, Performance monitoring.
    • Chromium: (Chrome, Edge Beta, Brave, Vivaldi, Opera, etc) - Accessibility Inspector, Contrast Ratio testing, Performance Monitoring, Lighthouse Audits (testing performance, best practices, accessibility and more).
    • Edge: Accessibility Inspector, Performance monitoring.
    • Safari: Accessibility Inspector, Performance monitoring.
    Firefox (left), Chrome, and Edge Beta (right) Dev Tools now analyse contrast ratios in the colour picker. The Chromium-based browsers also show curves on the colour picker to let you know which shades would meet the contrast requirements.
  11. Linc is a continuous delivery platform that makes testing the front end easier by automatically deploying a version of your website for every commit on every branch. One of the biggest hurdles when testing the front end is needing a live version of the site to view and test against. Linc makes sure you always have one.
  12. ESLint and Stylelint check your code for programmatic and stylistic errors, as well as helping keep formatting standard on projects with multiple developers. Adding a linter to your project not only helps you write better code, it can reduce simple errors that might be found during testing time. If you’re not writing JavaScript, there are plenty of alternatives for whatever language you’re writing in.

If you’re trying to run eslint in VS Code, make sure you don’t have the Beautify extension installed, as that will break things.

Eleven Optimised Images

When it comes to performance, images are where we take the biggest hit, with images accounting for over 50% of total transfer size for websites. Many websites are serving excessively large images “just in case”, but there’s actually a native HTML element that allows us to serve different image sizes based on the screen size or serve better image formats when the browser supports it (or both).

<!-- Serving different images based on the width of the screen -->
<picture>
    <source
        srcset="/img/banner_desktop.jpg"
        media="(min-width: 1200px)"
    />
    <source
        srcset="/img/banner_tablet.jpg"
        media="(min-width: 700px)"
    />
    <source
        srcset="/img/banner_mobile.jpg"
        media="(min-width: 300px)"
    />
    <img src="/img/banner_fallback.jpg">
</picture>

<!-- Serving different image formats based on browser compatibility -->
<picture>
    <source
        srcset="/banner.webp"
        type="image/webp"
    />
    <img src="/img/banner_fallback.jpg">
</picture>

Ten Linting Rules

A year ago, I didn’t use linting. It was mostly just me working on projects, and I can code properly right? But these days it’s one of the first things I add to a project as it saves me so much time (and has taught me a few things about JavaScript). Linting is a very personal choice, but there are plenty of customisations to make sure it’s doing what you want, and it’s available in a wide variety of languages (including linting for styling).

// .eslintrc
module.exports = {
    rules: {
        'no-var': 'error',
        'no-unused-vars': 1,
        'arrow-spacing': ['error', { before: true, after: true }],
        indent: ['error', 'tab'],
        'comma-dangle': ['error', 'always'],
        // standard plugin - options
        'standard/object-curly-even-spacing': ['error', 'either'],
        'standard/array-bracket-even-spacing': ['error', 'either'], },
}

// .stylelintrc
{
    "rules": {
        "color-no-invalid-hex": true,
        "indentation": [
            "tab",
            {
                "except": [
                    "value"
                ]
            }
        ],
        "max-empty-lines": 2,
    }
}

Nine Semantic Headings

No, I’m not saying you should use 9 levels of headings, but your webpage should have an appropriate number of semantic headings. When your users are accessing your webpage with a screen reader, they rely on landmarks like headings to tell them about the page. Similarly to how we would scan a page visually, screen readers give users a list of all headings on a page to allow them to scan through the sections and access the information faster.

When there aren’t any headings on a page (or headings are being used for their formatting rather than their semantic meaning), it makes it more difficult for anyone using a screen reader to understand and navigate the page. Make sure that you don’t skip heading levels on your page, and remember, you can always change the formatting on a p tag if you need to have something that looks like a heading but isn’t one.

<h1>Heading 1 - Page Title</h2>
<p>Traditionally you'll only see one h1 per page as it's the main page title</p>
<h2>Heading 2</h2>
<p>h2 helps to define other sections within the page. h2 must follow h1, but you can also have h2 following another h2.</p>
<h3>Heading 3</h3>
<p>h3 is a sub-section of h2 and follows similar rules to h2. You can have a h3 after h3, but you can't go from h1 to h3.</p>
<h4>Heading 4</h4>
<p>h4 is a sub-section of h3. You get the pattern?</p>

Eight Types of Colour Blindness

Testing colour contrast may not always be enough, as everyone perceives colour differently. Take the below colour combination (ignoring the fact that it doesn’t actually look nice). It has decent colour contrast and would meet the WCAG colour contrast requirements for AA standards – but what if one of your users was red-green colour blind? Would they be able to tell the difference?

http://colorsafe.co/ empowers designers with beautiful and accessible colour palettes based on WCAG Guidelines of text and background contrast ratios.

Red-green colour blindness is the most common form of colour blindness, but there are 8 different types affecting different parts of the colour spectrum, all the way up to complete colour blindness.

Protanopia
Inability to see red end of the colour spectrum.
Protanomaly
Difficulty seeing some shades of red.
Deuteranopia
Inability to see the green portion of the colour spectrum.
Deuteranomaly
Difficulty seeing some shades of green.
Tritanopia
Inability to see blue end of the colour spectrum.
Tritanomaly
Difficulty seeing some shades of blue.
Achromatopsia
Inability to see all parts of the colour spectrum, only able to perceive black, white and shades of grey.
Achromatomaly
Difficulty seeing all parts of the colour spectrum.

Seven (.0) Contrast Ratio

Sufficient colour contrast is perhaps one of the best steps to take for accessibility, as it benefits everyone. Having adequate contrast doesn’t just make the experience better for those with vision impairments, but it also helps those with situational impairments. Have you ever been in the sun and tried to read something on your screen? Whether you can view something when there’s glare could be as easy as making sure there’s enough contrast between the text and its background colour.

The WCAG have defined a contrast ratio of at least 4.5:1 for normal text (18.5px) and 3:1 for large text (24px) to meet AA accessibility standards, but this should be an absolute minimum and isn’t always readable. All four below examples have sufficient contrast to pass AA standards, but you might be hard pressed to read them when there’s glare or you have a dodgy monitor (even more so considering most websites use below 18.5px for their base font size).

Examples of 4.5:1 colour contrast

To meet the AAA standard you need to have a ratio of 7:1 for normal text and 4.5:1 for large text, which should be sufficient for those with 20/80 vision to read.

Six Front End Tests

  1. Adding default axe-core testing to Gatsby:
    //gatsby-config.js
    {
        resolve: 'gatsby-plugin-react-axe',
        options: {},
    },
  2. Running pa11y tests on homepage at various screen sizes:
    // tests/basic-a11y_home.js
    const pa11y = require('pa11y'),
        fs = require('file-system')
    
    runTest()
    
    async function runTest() {
        try {
            const results = await Promise.all([
                pa11y('http://localhost:8000', {
                    standard: 'WCAG2AA',
                    actions: [],
                    screenCapture: `${__dirname}/results/basic-a11y_home_mobile.png`,
                    viewport: {
                        width: 320,
                        height: 480,
                        deviceScaleFactor: 2,
                        isMobile: true,
                    },
                }),
                pa11y('http://localhost:8000', {
                    standard: 'WCAG2AA',
                    actions: [],
                    screenCapture: `${__dirname}/results/basic-a11y_home_desktop.png`,
                    viewport: {
                        width: 1280,
                        height: 1024,
                        deviceScaleFactor: 1,
                        isMobile: false,
                    },
                }),
            ])
    
            fs.writeFile('tests/results/basic-a11y_home.json', JSON.stringify(results), err => {
                console.log(err)
            })
        } catch (err) {
            console.error(err.message)
        }
    }
  3. Running pa11y tests on a blog post template at various screen sizes:
    // tests/basic-a11y_post.js
    const pa11y = require('pa11y'),
        fs = require('file-system')
    
    runTest()
    
    async function runTest() {
        try {
            const results = await Promise.all([
                pa11y('http://localhost:8000/template', {
                    standard: 'WCAG2AA',
                    actions: [],
                    screenCapture: `${__dirname}/results/basic-a11y_post_mobile.png`,
                    viewport: {
                        width: 320,
                        height: 480,
                        deviceScaleFactor: 2,
                        isMobile: true,
                    },
                }),
                pa11y('http://localhost:8000/template', {
                    standard: 'WCAG2AA',
                    actions: [],
                    screenCapture: `${__dirname}/results/basic-a11y_post_desktop.png`,
                    viewport: {
                        width: 1280,
                        height: 1024,
                        deviceScaleFactor: 1,
                        isMobile: false,
                    },
                }),
            ])
    
            fs.writeFile('tests/results/basic-a11y_post.json', JSON.stringify(results), err => {
                console.log(err)
            })
        } catch (err) {
            console.error(err.message)
        }
    }
  4. Running BackstopJS on a homepage and blog post template at various screen sizes:
    // backstop.json
    {
      "id": "backstop_default",
      "viewports": [
        {
          "label": "phone",
          "width": 320,
          "height": 480
        },
        {
          "label": "tablet",
          "width": 1024,
          "height": 768
        },
        {
          "label": "desktop",
          "width": 1280,
          "height": 1024
        }
      ],
      "onBeforeScript": "puppet/onBefore.js",
      "onReadyScript": "puppet/onReady.js",
      "scenarios": [
        {
          "label": "Blog Homepage",
          "url": "http://localhost:8000",
          "delay": 2000,
          "postInteractionWait": 0,
          "expect": 0,
          "misMatchThreshold": 1,
          "requireSameDimensions": true
        },
        {
          "label": "Blog Post",
          "url": "http://localhost:8000/template",
          "delay": 2000,
          "postInteractionWait": 0,
          "expect": 0,
          "misMatchThreshold": 1,
          "requireSameDimensions": true
        }
      ],
      "paths": {
        "bitmaps_reference": "backstop_data/bitmaps_reference",
        "bitmaps_test": "backstop_data/bitmaps_test",
        "engine_scripts": "backstop_data/engine_scripts",
        "html_report": "backstop_data/html_report",
        "ci_report": "backstop_data/ci_report"
      },
      "report": [
        "browser"
      ],
      "engine": "puppeteer",
      "engineOptions": {
        "args": [
          "--no-sandbox"
        ]
      },
      "asyncCaptureLimit": 5,
      "asyncCompareLimit": 50,
      "debug": false,
      "debugWindow": false
    }
  5. Running Cypress tests on the homepage:
    // cypress/integration/basic-test_home.js
    describe('Blog Homepage', () => {
        beforeEach(() => {
            cy.visit('http://localhost:8000')
        })
        it('contains "Amy Goes to Perth" in the title', () => {
            cy.title().should('contain', 'Amy Goes to Perth')
        })
        it('contains posts in feed', () => {
            cy.get('.article-feed').find('article')
        })
        it('all posts contain title', () => {
            cy.get('.article-feed')
                .find('article')
                .get('h2')
        })
    })
  6. Running Cypress tests on a blog post template at various screen sizes:
    // cypress/integration/basic-test_post.js
    
    describe('Blog Post Template', () => {
        beforeEach(() => {
            cy.visit('http://localhost:8000/template')
        })
        it('contains "Amy Goes to Perth" in the title', () => {
            cy.title().should('contain', 'Amy Goes to Perth')
        })
        it('has visible post title', () => {
            cy.get('h1').should('be.visible')
        })
        it('has share icons', () => {
            cy.get('.share-icons a').should('be.visible')
        })
        it('has working share icons', () => {
            cy.get('.share-icons a').click({ multiple: true })
        })
        it('has a visible author profile image', () => {
            cy.get('.author img').should('be.visible')
        })
    })
    
    describe('Mobile Blog Post Template', () => {
        beforeEach(() => {
            cy.viewport('samsung-s10')
            cy.visit('http://localhost:8000/template')
        })
        it('contains "Amy Goes to Perth" in the title', () => {
            cy.title().should('contain', 'Amy Goes to Perth')
        })
        it('has visible post title', () => {
            cy.get('h1').should('be.visible')
        })
        it('has share icons', () => {
            cy.get('.share-icons .share-link').should('be.visible')
        })
        it('has a visible author profile image', () => {
            cy.get('.author img').should('be.visible')
        })
    })

Five Browser Types

Browser testing may be the bane of our existence, but it’s gotten easier, especially when you know the secret:

Not every browser needs to look the same.

Now, this may differ depending on your circumstances, but your website doesn’t have to match pixel for pixel across all browsers. As long as it’s on-brand and is useable across all browsers (this is where a good solid HTML foundation is useful), it’s ok for your site to look a little different between browsers.

While the browsers you test in will differ depending on your user base, the main ones you want to be covering are:

  • Chrome/Chromium
  • Firefox
  • Safari
  • Internet Explorer
  • Edge

Make sure you’re testing these browsers on both desktop and mobile/tablet as well, sometimes their level of support or rendering engine will differ between devices – for example, iOS Chrome uses the Safari rendering engine, so something that works on Android Chrome may not work on iOS Chrome.

Four Types of Test

When it comes to testing the front end, there are a few different areas that we can cover:

  1. Accessibility Testing: doing accessibility testing properly usually involves getting an expert to run through your website, but there are several automated tests that you can run against various standard levels.
  2. Performance Testing: performance testing does technically bleed into the back end as well, but there are plenty of things that can be done from a front end perspective. Making sure the images are optimised, our code is clean and minified, and even optimising fonts using features like the font-display property. No amount of optimising the server and back end will matter if it takes forever for the front end to appear in a browser.
  3. Visual Regression Testing: we’ve all been in the position where changing one line of CSS somewhere has affected another section of the website. Visual regression testing helps prevent that. By using a tool that compares before and after screenshots against one another to flag up what’s changed, you can be sure that style changes won’t bleed into unintended areas of the site.
  4. Browser/device testing: while we all want our users to be running the most recent version of Chrome or Firefox, they may still be using the inbuilt browser on their DVD player – so we need to test various browsers, platforms and devices to make sure that our website can be accessed on whatever device they use.

Three Shaken Trees

Including (and therefore requiring your users to download) things that you’re not using affects the performance of your application. Are you forcing them to download the entire lodash library when you’re only using 2 functions? While a couple of unused lines of code may not seem like a huge performance hit, it can greatly affect users with slower devices or internet connections, as well as cluttering up your code with unused functions and dependencies. This can be set up on your bundler – Webpack and Parcel both have guides for tree shaking, and Gatsby has a plugin to enable it.

Two Image Types

While there are several different types of images, most of the time they fall into one of two categories:

Informative
The image represents/conveys important information that isn’t conveyed by the content surrounding it.
Decorative
The image only adds visual decoration to a page.

From these two categories, we can then determine if we need to provide alternative text for an image. If an image is purely decorative, then we add alt="" to let screen readers know that it’s not important. But if an image is informative, then we need to be supplying a text alternative that describes the picture for anyone who’s using a screen reader or isn’t able to see the image (remember the days when a standard internet connection took a long time to load a page and you saw alt text before an image loaded).

<img src="./nice-picture.jpg" alt="" />
<img src="./important-graphic.png" alt="This is a picture of something important to help add meaning to the text around me" />

If you have a lot of images with missing alt text, look into services that can auto-generate alt text based on image recognition services.

One Source Controlled Deployment Pipeline

While front end tests are harder to automate, running them through a source control and deployment pipeline helps track changes and eliminates issues where “it works on my computer”. Whether you’re running tests as part of the PR process, or simply against every commit that comes through, running tests automatically as part of your process makes every developer’s life easier and helps keep code quality at a high standard.


We already knew that testing was important, and your project can’t be run unless all your unit and integration tests are written (and pass), but often we forget about testing the front end. There are so many different tests we need to be running on the front end, it’s hard to work out what your need to test for and where to start.

Hopefully this has given you a bit of insight to front end testing, and some Christmas cheer to take you into the holidays.


About the author

Amy wears many hats as a freelance developer, business owner and conference addict. She regularly shares her knowledge with her peers and the next generation of developers by mentoring, coaching, teaching and feeding into the tech community in many ways.

Amy can be found volunteering her time with Fenders, ACS, SheCodes (formerly Perth Web Girls) and MusesJS (formerly NodeGirls). She also works as an evangelist for YOW! Conferences, is a Twilio Champion and has been nominated for the WiTWA awards for the last 2 years.

In her spare time Amy shares her knowledge and experience on her blogs and speaking at conferences. She has previously given keynotes at multiple events as well as speaking at several international conferences in the US and Europe.

More articles by Amy




ng

Beautiful Scrolling Experiences – Without Libraries

Michelle Barker appears as one of a heavenly host, coming forth with scroll in hand to pronounce an end to janky scrolljacking! Unto us a new specification is born, in the city of TimBL, and its name shall be called Scroll Snap.


Sponsor: Order any Standard paperback(s) and get a surprise gift card in the box for YOU. While supplies last, from your pals at A Book Apart!


One area where the web has traditionally lagged behind native platforms is the perceived “slickness” of the app experience. In part, this perception comes from the way the UI responds to user interactions – including the act of scrolling through content.

Faced with the limitations of the web platform, developers frequently reach for JavaScript libraries and frameworks to alter the experience of scrolling a web page – sometimes called “scroll-jacking” – not always a good thing if implemented without due consideration of the user experience. More libraries can also lead to page bloat, and drag down a site’s performance. But with the relatively new CSS Scroll Snap specification, we have the ability to control the scrolling behaviour of a web page (to a degree) using web standards – without resorting to heavy libraries. Let’s take a look at how.

Scroll Snap

A user can control the scroll position of a web page in a number of ways, such as using a mouse, touch gesture or arrow keys. In contrast to a linear scrolling experience, where the rate of scroll reflects the rate of the controller, the Scroll Snap specification enables a web page to snap to specific points as the user scrolls. For this, we need a fixed-height element to act as the scroll container, and the direct children of that element will determine the snap points. To demonstrate this, here is some example HTML, which consists of a <div> containing four <section> elements:

<div class="scroll-container">
  <section>
    <h2>Section 1</h2>
  </section>
  <section>
    <h2>Section 2</h2>
  </section>
  <section>
    <h2>Section 3</h2>
  </section>
  <section>
    <h2>Section 4</h2>
  </section>
</div>

Scroll snapping requires the presence of two main CSS properties: scroll-snap-type and scroll-snap-align. scroll-snap-type applies to the scroll container element, and takes two keyword values. It tells the browser:

  • The direction to snap
  • Whether snapping is mandatory

scroll-snap-align is applied to the child elements – in this case our <section>s.

We also need to set a fixed height on the scroll container, and set the relevant overflow property to scroll.

.scroll-container {
  height: 100vh;
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
}

section {
  height: 100vh;
  scroll-snap-align: center;
}

In the above example, I’m setting the direction in the scroll-snap-type property to y to specify vertical snapping. The second value specifies that snapping is mandatory. This means that when the user stops scrolling their scroll position will always snap to the nearest snap point. The alternative value is proximity, which determines that the user’s scroll position will be snapped only if they stop scrolling in the proximity of a snap point. (It’s down to the browser to determine what it considers to be the proximity threshold.)

If you have content of indeterminate length, which might feasibly be larger than the height of the scroll container (in this case 100vh), then using a value of mandatory can cause some content to be hidden above or below the visible area, so is not recommended. But if you know that your content will always fit within the viewport, then mandatory can produce a more consistent user experience.

See the Pen Simple scroll-snap example by Michelle Barker (@michellebarker) on CodePen.

In this example I’m setting both the scroll container and each of the sections to a height of 100vh, which affects the scroll experience of the entire web page. But scroll snapping can also be implemented on smaller components too. Setting scroll snapping on the x-axis (or inline axis) can produce something like a carousel effect.

In this demo, you can scroll horizontally scroll through the sections:

See the Pen Carousel-style scroll-snap example by Michelle Barker (@michellebarker) on CodePen.

The Intersection Observer API

By implementing the CSS above, our web page already has a more native-like feel to it. To improve upon this further we could add some scroll-based transitions and animations. We’ll need to employ a bit of Javascript for this, using the Intersection Observer API. This allows us to create an observer that watches for elements intersecting with the viewport, triggering a callback function when this occurs. It is more efficient than libraries that rely on continuously listening for scroll events.

We can create an observer that watches for each of our scroll sections coming in and out of view:

const sections = [...document.querySelectorAll('section')]

const options = {
  rootMargin: '0px',
  threshold: 0.25
}

const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.intersectionRatio >= 0.25) {
      target.classList.add("is-visible");
    } else {
      target.classList.remove("is-visible");
    }
  })
}

const observer = new IntersectionObserver(callback, options)

sections.forEach((section, index) => {
  observer.observe(section)
})

In this example, a callback function is triggered whenever one of our sections intersects the container by 25% (using the threshold option). The callback adds a class of is-visible to the section if it is at least 25% in view when the intersection occurs (which will take effect when the element is coming into view), and removes it otherwise (when the element is moving out of view). Then we can add some CSS to transition in the content for each of those sections:

section .content {
  opacity: 0:
}

section.is-visible .content {
  opacity: 1;
  transition: opacity 1000ms:
}

This demo shows it in action:

See the Pen Scrolling with Intersection Observer by Michelle Barker (@michellebarker) on CodePen.

You could, of course, implement some much more fancy transition and animation effects in CSS or JS!

As an aside, it’s worth pointing out that, in practice, we shouldn’t be setting opacity: 0 as the default without considering the experience if JavaScript fails to load. In this case, the user would see no content at all! There are different ways to handle this: We could add a .no-js class to the body (which we remove on load with JS), and set default styles on it, or we could set the initial style (before transition) with JS instead of CSS.

Position: sticky

There’s one more CSS property that I think has the potential to aid the scroll experience, and that’s the position property. Unlike position: fixed, which locks the position of an element relative to the nearest relative ancestor and doesn’t change, position: sticky is more like a temporary lock. An element with a position value of sticky will become fixed only until it reaches the threshold of its parent, at which point it resumes relative positioning.

By “sticking” some elements within scroll sections we can give the impression of them being tied to the action of scrolling between sections. It’s pretty cool that we can instruct an element to respond to it’s position within a container with CSS alone!

Browser support and fallbacks

The scroll-snap-type and scroll-snap-align properties are fairly well-supported. The former requires a prefix for Edge and IE, and older versions of Safari do not support axis values. In newer versions of Safari it works quite well. Intersection Observer similarly has a good level of support, with the exception of IE.

By wrapping our scroll-related code in a feature query we can provide a regular scrolling experience as a fallback for users of older browsers, where accessing the content is most important. Browsers that do not support scroll-snap-type with an axis value would simply scroll as normal.

@supports (scroll-snap-type: y mandatory) {
  .scroll-container {
    height: 100vh;
    overflow-y: scroll;
    scroll-snap-type: y mandatory;
  }

  section {
    height: 100vh;
    scroll-snap-align: center;
  }
}

The above code would exclude MS Edge and IE, as they don’t support axis values. If you wanted to support them you could do so using a vendor prefix, and using @supports (scroll-snap-type: mandatory) instead.

Putting it all together

This demo combines all three of the effects discussed in this article.

Summary

Spending time on scroll-based styling might seem silly or frivolous to some. But I believe it’s an important part of positioning the web as a viable alternative to native applications, keeping it open and accessible. While these new CSS features don’t offer all of the control we might expect with a fully featured JS library, they have a major advantage: simplicity and reliability. By utilising web standards where possible, we can have the best of both worlds: Slick and eye-catching sites that satisfy clients’ expectations, with the added benefit of better performance for users.


About the author

Michelle is a Lead Front End Developer at Bristol web agency Atomic Smash, author of front-end blog CSS { In Real Life }, and a Mozilla Tech Speaker. She has written articles for CSS Tricks, Smashing Magazine, and Web Designer Magazine, to name a few. She enjoys experimenting with new CSS features and helping others learn about them.

More articles by Michelle




ng

Gift Giving to the World (Wide Web)

Frances Berriman asks us to give the gift of consideration to those who are using the web on constricted devices such as low-end smart phones or feature phones. Christmas is a time of good will to all, and as Bugsy Malone reminds us, you give a little love and it all comes back to you.


If I was given the job of Father Christmas with all my human limitations, apparently it would take me something like 6 months at non-stop full speed to deliver gifts to every kid on the planet. The real Father Christmas has the luxury of magic when it comes to delivering millions of gifts in just one night, but the only magical platform at my disposal is the world wide web, so I propose switching to digital gift cards and saving the reindeer feed.

300 million people are set to come online for the very first time in 2020, and a majority of those will be doing so via mobile phones (smart- and feature-phones). If we want those new users to have a great time online, spending those gift cards, we need to start thinking about their needs and limitations.

Suit up

We might not be hopping on the sleigh for these deliveries, but let’s suit up for the journey and get the tools we need to start testing and checking how our online gift-receivers will be enjoying their online shopping experience.

Of course, the variety of phones and OSs out there is huge and varied, but we have a few options out there to get a sense for the median. Here’s a few suggestions on where to start:

  • Never has there been a better time to advocate at your workplace for a device testing suite or lab.
  • You can also just pick up a low-end phone for a few bucks and spend some real time using it and getting a sense for how it feels to live with it every day. May I suggest the Nokia 2 or the Moto E6 - both very representative devices of the sort our new visitors will be on.
  • You’ve also got WebPageTest.org at your disposal, where you can emulate various phones and see your sites rendered in real-time to get a sense of what an experience may look like for your users.
  • You’ll also want to set yourself some goals. A performance budget, for example, is a good way to know if the code you’re shipping hits the mark in a more programmatic way.

Gift wrap

Many of us began our internet lives on desktop machines, and thanks to Moore’s law, these machines have been getting ever more powerful every year with more CPUs and memory at our disposal. The mobile phone landscape somewhat resets us on what hardware capacity is available on the client-side of our code, so it’s time to lighten the load.

What we see in the landscape of phones today is a huge spread of capabilities and CPU speeds, storage capacity and memory. And the gap between the haves and the have-nots is widening, so we have a huge task to deal with in meeting the needs of such a varied audience.

As far as possible, we should try to:

  • Keep processing off the client - do anything you can server-side. Consider a server-side render (hold the <script>, thanks) for anything relatively static (including cached frequent queries and results) to keep client-side JavaScript to the minimum. This way you’re spending your CPU, not the user’s.
  • Avoid sending everything you have to to the end user. Mobile-first access also means data-plan-first access for many, which means they may be literally paying in cold-hard cash for everything you send over the wire – or may be experiencing your site over a degraded “4G” connection towards the end of the month.
  • Aggressively cache assets to prevent re-downloading anything you’ve sent before. Don’t make the user pay twice if they don’t have to.
  • Progressively load additional assets and information as the user requests them, rather than a big upfront payload, that way you’re giving the end user a little more choice about whether they want or need that extra data set.

This is all to say that as web developers, we have a lot more control over how and when we deliver the meat of our products - unlike native apps that generally send the whole experience down as one multi-megabyte download that our 4G and data-strapped users can’t afford.

Make a wish

Finally, it’s time for your gift recipients to go out onto the web and find whatever their greatest wish is. For many, that’s going to begin when they first turn on their phone and see all those enticing icons on their home screen. Opening a browser may not be their first port of call.

They’ll be primed to look for sites and information through the icon-heavy menu that most mobile OSs use today, and they will be encouraged to find new experiences through the provided app store interface.

The good news is that web experience can be found in many modern app-stores today.

For example, if you build an app using Trusted Web Activities, the Google Play Store will list your web site right alongside native apps and allow users to install them on their phones. Samsung and Microsoft have similar options without the extra step of creating a TWA - they’ll list any Progressive Web App in their stores. Tools like Microsoft’s PWA Builder and Llama Pack are making this easier than ever.

If your users are primed to search for new experiences via a search engine instead, then they’ll benefit from the work you’ve put in to list them in app stores regardless, as PWAs are first and foremost about making websites mobile-friendly, regardless of point of sale. A PWA will provide them with offline support, service works, notifications and much more.

We do have a grinch in this story, however.

Apple’s iOS explicitly does not allow your website to be listed in their app store, so sadly you’ll have a harder time reaching those users. But it is possible! Fortunately, iOS isn’t as all-dominating world wide as it is in the tech community, selling only around 10-15% of smartphones out in the world.

The best present

The WWW is a wonderful gift that we received over 30 years ago and, as web developers, we get to steward and share this truly global, open, platform with millions of people every day. Let’s take care of it by building and sharing experiences that truly meet the needs of everyone.


About the author

Frances Berriman is a San Francisco-based British-born designer and web developer who blogs at fberriman.com. She’s done all sorts of things, but has a special soft spot for public sector projects, and has worked for the Government Digital Service, building GOV.UK, Code for America, Nature Publishing and the BBC and is currently Head of UX and Product Design at Netlify.

More articles by Frances




ng

Making Distributed Working Work

Anna Debenham harnesses up the huskies and puts them to work to figure out how teams distributed across multiple locations can work effectively to all pull in the same direction. With modern workforces distributed from north pole to south, can they all be kept running in step?


Four years ago, I started working at a small startup called Snyk that’s based in two locations – London and Tel Aviv. The founders made it clear they wanted to grow headcount in both locations at the same rate, and for the design and engineering skillsets between the two offices to be evenly spread. We’re now at over 200 people and we’re still staying true to that vision, but only by completely changing how we were used to working.

The trend for fully distributed teams is on the rise – companies like InVision and GitLab have entirely remote employees. Snyk is somewhere in between, with small hubs of global team members in homes and shared offices globally alongside our main London, Tel Aviv, Boston, Ottawa and Bay Area offices.

Our R&D teams are based entirely in London or Tel Aviv, with a few employees working around Europe. Rather than have Team A working in one office and Team B working in another, we’ve deliberately designed it so that no R&D team at Snyk has all its members in one location. We could design our teams to be all co-located so that everyone’s in the same room, but we don’t.

When I explain this setup to people, I’ll often get a response of bewilderment – why do it this way? It sounds like a pain! Increasingly though, the reaction is positive – usually from people who’ve worked in a distributed team before where departments are split neatly between locations. They’ve experienced an “us vs them” culture, with work being thrown over the fence to designers or engineers in different timezones. They’ve been at the mercy of the decision makers who are all in the head office. This is exactly what we wanted to avoid. We wanted the company to feel like one team, across many locations.

It’s not perfect – I do miss the things that working in the same location brings such as collaborating on a whiteboard, or having planning documents stuck on the wall for the team to refer to. Pre-distributed working, I used to sit next to a designer and we’d bounce ideas off each other. Now I have to make the extra effort to schedule something in. Managing people remotely is also tough – I can’t easily see that a team member is having a bad day and make them a cup of tea.

But on the whole, it works pretty well for us. The time difference between London and Tel Aviv is a comfy 2 hours, and in Tel Aviv, the week runs from Sunday to Thursday, meaning there’s just a single day in the week when all our teams aren’t working. This makes the week feel like the ebb and flow of a tide – my Mondays are very busy, but on Fridays, half the team is off so there are barely any meetings – ideal for deep focus time.

So how do we make this distributed-but-also-co-located hybrid thing work?

Level the playing field

Firstly, that “us vs them” mentality I mentioned is the key thing to avoid to maintain a positive distributed work culture. Avoid the term “remote team”, as that has a sense of otherness. Instead, refer to your team as “distributed”. It’s such a small change that has the effect of bringing everyone onto the same level.

Also, consider your video conferencing etiquette – if you’ve got a large part of your team in one location, with just one or two members who are dialling in, you could end up with a very one-sided conversation. The room with the most people in it has a habit of forgetting the person they can’t easily see. Even if you’re in the same room, dial in individually so that everyones faces are the same size, and you’re addressing all the participants rather than just those in the same room as you.

Invest in tools that help communication

Early on, we invested in tools that would help make communication between locations as seamless as possible. I’m not talking about those screens with wheels that follow co-workers around a room to recreate a manager breathing down their neck (although now I think of it…). I’m talking about the familiar ones like Slack, Zoom and Notion.

Use a single tool where possible to reduce friction between teams so there’s no confusion as to whether you’re having a call over Google Hangouts, Zoom, Skype or whatever else is fashionable to use this year. Same with meeting notes – keep them in one place rather than scattered across Dropbox, Email and Google Docs.

Remote pair programming has also got a lot easier. We used ScreenHero before it got acquired and lost its remote control functionality – but there are some great alternatives out there like USE Together. You might also have collaboration tools built into your code editor, like Visual Studio’s Live Share, and Atom’s Teletype.

If teams are complaining about bad audio, don’t skimp – invest in better microphones, speakers and sound-proofing. You won’t get the benefits of working as a distributed team if there’s a barrier between communication. Ensure the internet is stable in all locations. Also, it sounds basic but make sure teams have somewhere to take a call in the first place, particularly 1:1s which shouldn’t be done in the open. Previous places I’ve contracted at had people dialling into meetings in stairwells, shower rooms and even toilet cubicles. Take care not to make the experience of working in a distributed team end up harming the experience of working in an office.

Open a window

For as long as we’ve had offices, we’ve had a fixed camera and TV screen setup between them that acts as a “window” between locations. The camera is on all the time, and we turn the microphone on once a day for standup (or whenever someone wants to say hi). When I turn on the TV in the morning, I can see the Tel Aviv office already working. At midday, our Boston office comes online, followed shortly after by our Ottawa office. It’s incredible what a difference this has made to make us feel more like one office.

We’ve positioned one of the cameras next to our dining area so we can eat together. Another camera is honed in on a dog bed in the corner of the office (sometimes there’s a dog in it!).

Distributed meetings

With the time differences and weekday shift, there’s a condensed timeframe in which we can collaborate. It’s not as bad as it could be (I pity my fellow Londoners who work for companies based in California), but the hours between 9am and 4pm Monday to Thursday for us are at a premium. This means the meetings we have need to be a good use of everyone’s time. When we can’t find a time that works for everyone, we record the meeting. But even if everyone can make it, we still take notes.

The notebook brand Field Notes have a slogan “I’m not writing it down to remember it later, I’m writing it down to remember it now.”. This is a reminder that it’s not always the notes themselves that are useful, but the act of taking them. Where they’re really powerful is when you share them in real time. In Kevin Hoffman’s book ‘Meeting Design’, he recommends the notetaker shares their screen while taking notes so that everyone can participate in making sure those notes are accurate. Having the notes on the screen also helps focus the conversation – particularly if you have an agenda template to start with. It means you’ve got a source of truth for someone who mis-remembers a conversation, and you’ve got something to look back on in the next meeting so you don’t repeat yourselves.

Another tip we’ve taken from Kevin’s book is to have a kanban board for standing meetings, where everyone can add a topic. That way, you always have a backlog of topics to discuss in the meeting. If there aren’t any, you can cancel the meeting!

We use Notion’s kanban template for our sync meeting notes. Anyone can add a topic before (or during) the meeting and we go through each of them in order. We add notes and action points to the topic card.

Don’t get into bad habits when you’re lucky enough to be sharing a single space – keep documenting conversations and decisions in the same way you would with a distributed team, so that future you can remember, and future team members can gather that context.

Team bonding

I always think the best way to bonding with people is over a meal – isn’t that what Christmas dinner is great for? As a distributed team, we can’t do that. We could try and recreate it (even just for the comedy value), but it’s really not the same. We have to try something different.

Enter Eurovision. For those of you outside Europe, imagine a cheesy pop song contest where each country performs their own song and everyone votes for the winner. This year, it was held in Tel Aviv, so dozens of us sat down to watch the live stream. We set up a Eurovision Slack channel and shared our horror in real time.

But Eurovision only happens ones a year, so we’ve extended shared experiences into multiple “hobby” Slack channels: we have one for food fans (#fun-foodies), football fans (#fun-footies), and even sourdough fans (#fun-sourdough). There’s also a weekly “drink and sync” where office-less team members join a video call and chat over a beer, coffee, or juice depending on the time of day for those that dial in. One team runs a movie club where they choose a video that’s relevant to their team’s work (such as a conference talk) and watch it together at the same time.

Onboarding new team members can feel quite impersonal if their manager isn’t in the same office. Starting your first day in an office full of strangers, where the only interaction with your manager is over a video call can feel daunting. And as a manager, I get anxious about my new hire’s first day – was there someone there to greet them and show them where they sit? Was everything set up for them? Did they have someone to eat lunch with? So we’ve been rolling out an “onboarding buddy” scheme. This is someone local who can help the new hire settle in to their new surroundings. It’s someone to chat to, share a coffee with, and generally look out for them.

We also use a Slack app called Donut which pairs employees up for informal chats to get to know each other. You get paired with someone random in the company and it helps you schedule a call with them. This is to encourage cross-pollination across teams and locations.

What distributed teamwork has taught us

There’s a lot that we’ve learnt about working well as a distributed team. We try and recreate the good things about sharing a physical space, and make them feel just as natural in the digital space, while also compensating for the lack of intimacy from being thousands of miles apart.

Mel Choyce’s 24 ways article Surviving—and Thriving—as a Remote Worker stresses the value of remote working, and the long term benefits it has had.

Working remotely has made me a better communicator largely because I’ve gotten into the habit of making written updates.

I think in a lot of ways, the distance has brought us closer. We make more of an effort to check in on how each other is doing. We document as much as we can, which really helps new hires get up to speed quickly.

By identifying what we find valuable about working in the same room, and translating that to work across locations, we find collaboration easier because we’re no longer strangers to each other. We might not be able to have those water-cooler moments in the physical realm, but we’ve done a good job of replicating that online.


About the author

Anna Debenham lives in London and is a Product Manager at Snyk.

She’s the author of Front-end Style Guides, and when she’s not playing on them, she’s testing as many game console browsers as she can get her hands on.

More articles by Anna




ng

Building a Dictaphone Using Media Recorder and getUserMedia

Chris Mills brushes up his shorthand and shows how the MediaStream Recording API in modern browsers can be used to capture audio directly from the user’s device. Inching ever closer to the capabilities of native software, it truly is an exciting time to be a web developer.


The MediaStream Recording API makes it easy to record audio and/or video streams. When used with MediaDevices.getUserMedia(), it provides an easy way to record media from the user’s input devices and instantly use the result in web apps. This article shows how to use these technologies to create a fun dictaphone app.

A sample application: Web Dictaphone

To demonstrate basic usage of the MediaRecorder API, we have built a web-based dictaphone. It allows you to record snippets of audio and then play them back. It even gives you a visualisation of your device’s sound input, using the Web Audio API. We’ll just concentrate on the recording and playback functionality in this article, for brevity’s sake.

You can see this demo running live, or grab the source code on GitHub. This has pretty good support on modern desktop browsers, but pretty patchy support on mobile browsers currently.

Basic app setup

To grab the media stream we want to capture, we use getUserMedia(). We then use the MediaRecorder API to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back.

We’ll first declare some variables for the record and stop buttons, and the <article> that will contain the generated audio players:

const record = document.querySelector('.record');
const stop = document.querySelector('.stop');
const soundClips = document.querySelector('.sound-clips');

Next, we set up the basic getUserMedia structure:

if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
   console.log('getUserMedia supported.');
   navigator.mediaDevices.getUserMedia (
      // constraints - only audio needed for this app
      {
         audio: true
      })

      // Success callback
      .then(function(stream) {

      })

      // Error callback
      .catch(function(err) {
         console.log('The following `getUserMedia` error occured: ' + err);
      }
   );
} else {
   console.log('getUserMedia not supported on your browser!');
}

The whole thing is wrapped in a test that checks whether getUserMedia is supported before running anything else. Next, we call getUserMedia() and inside it define:

  • The constraints: Only audio is to be captured for our dictaphone.
  • The success callback: This code is run once the getUserMedia call has been completed successfully.
  • The error/failure callback: The code is run if the getUserMedia call fails for whatever reason.

Note: All of the code below is found inside the getUserMedia success callback in the finished version.

Capturing the media stream

Once getUserMedia has created a media stream successfully, you create a new Media Recorder instance with the MediaRecorder() constructor and pass it the stream directly. This is your entry point into using the MediaRecorder API — the stream is now ready to be captured into a <Blob>, in the default encoding format of your browser.

const mediaRecorder = new MediaRecorder(stream);

There are a series of methods available in the MediaRecorder interface that allow you to control recording of the media stream; in Web Dictaphone we just make use of two, and listen to some events. First of all, MediaRecorder.start() is used to start recording the stream once the record button is pressed:

record.onclick = function() {
  mediaRecorder.start();
  console.log(mediaRecorder.state);
  console.log("recorder started");
  record.style.background = "red";
  record.style.color = "black";
}

When the MediaRecorder is recording, the MediaRecorder.state property will return a value of “recording”.

As recording progresses, we need to collect the audio data. We register an event handler to do this using mediaRecorder.ondataavailable:

let chunks = [];

mediaRecorder.ondataavailable = function(e) {
  chunks.push(e.data);
}

Last, we use the MediaRecorder.stop() method to stop the recording when the stop button is pressed, and finalize the Blob ready for use somewhere else in our application.

stop.onclick = function() {
  mediaRecorder.stop();
  console.log(mediaRecorder.state);
  console.log("recorder stopped");
  record.style.background = "";
  record.style.color = "";
}

Note that the recording may also stop naturally if the media stream ends (e.g. if you were grabbing a song track and the track ended, or the user stopped sharing their microphone).

Grabbing and using the blob

When recording has stopped, the state property returns a value of “inactive”, and a stop event is fired. We register an event handler for this using mediaRecorder.onstop, and construct our blob there from all the chunks we have received:

mediaRecorder.onstop = function(e) {
  console.log("recorder stopped");

  const clipName = prompt('Enter a name for your sound clip');

  const clipContainer = document.createElement('article');
  const clipLabel = document.createElement('p');
  const audio = document.createElement('audio');
  const deleteButton = document.createElement('button');

  clipContainer.classList.add('clip');
  audio.setAttribute('controls', '');
  deleteButton.innerHTML = "Delete";
  clipLabel.innerHTML = clipName;

  clipContainer.appendChild(audio);
  clipContainer.appendChild(clipLabel);
  clipContainer.appendChild(deleteButton);
  soundClips.appendChild(clipContainer);

  const blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
  chunks = [];
  const audioURL = window.URL.createObjectURL(blob);
  audio.src = audioURL;

  deleteButton.onclick = function(e) {
    let evtTgt = e.target;
    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
  }
}

Let’s go through the above code and look at what’s happening.

First, we display a prompt asking the user to name their clip.

Next, we create an HTML structure like the following, inserting it into our clip container, which is an <article> element.

<article class="clip">
  <audio controls></audio>
  <p>_your clip name_</p>
  <button>Delete</button>
</article>

After that, we create a combined Blob out of the recorded audio chunks, and create an object URL pointing to it, using window.URL.createObjectURL(blob). We then set the value of the <audio> element’s src attribute to the object URL, so that when the play button is pressed on the audio player, it will play the Blob.

Finally, we set an onclick handler on the delete button to be a function that deletes the whole clip HTML structure.

So that’s basically it — we have a rough and ready dictaphone. Have fun recording those Christmas jingles! As a reminder, you can find the source code, and see it running live, on the MDN GitHub.


This article is based on Using the MediaStream Recording API by Mozilla Contributors, and is licensed under CC-BY-SA 2.5.


About the author

Chris Mills manages the MDN web docs writers’ team at Mozilla, which involves spreadsheets, meetings, writing docs and demos about open web technologies, and occasional tech talks at conferences and universities. He used to work for Opera and W3C, and enjoys playing heavy metal drums and drinking good beer.

More articles by Chris




ng

Five Interesting Ways to Use Array.reduce() (And One Boring Way)

Chris Ferdinandi turns the heat down low and lets the sauce reduce while we take a look at how to add spice to our source with a sprinkling of Array.reduce(). Just a little ingenuity with the humblest of functions.


Of all the modern array methods, the one I had the hardest time wrapping my head around was Array.reduce().

On the surface, it seems like a simple, boring method that doesn’t do much. But below its humble exterior, Array.reduce() is actually a powerful, flexible addition to your developer toolkit.

Today, we’re going to look at some cool things you can do with Array.reduce().

How Array.reduce() works

Most of the modern array methods return a new array. The Array.reduce() method is a bit more flexible. It can return anything. Its purpose is to take an array and condense its content into a single value.

That value can be a number, a string, or even an object or new array. That’s the part that’s always tripped me up – I didn’t realize just how flexible it is!

The syntax

The Array.reduce() accepts two arguments: a callback method to run against each item in the array, and a starting value.

The callback also accepts two arguments: the accumulator, which is the current combined value, and the current item in the loop. Whatever you return is used as the accumulator for the next item in the loop. On the very first loop, that starting value is used instead.

var myNewArray = [].reduce(function (accumulator, current) {
  return accumulator;
}, starting);

Let’s look at some examples to make this all tangible.

1. Adding numbers together

Let’s say you had an array of numbers that you wanted to add together. Using Array.forEach(), you might do something like this:

var total = 0;

[1, 2, 3].forEach(function (num) {
  total += num;
});

This is the cliche example for using Array.reduce(). I find the word accumulator confusing, so in this example, I’m calling it sum, because that’s what it is.

var total = [1, 2, 3].reduce(function (sum, current) {
  return sum + current;
}, 0);

Here, we pass in 0 as our starting value.

In the callback, we add the current value to the sum, which has our starting value of 0 on the first loop, then 1 (the starting value of 0 plus the item value of 1), then 3 (the sum value of 1 plus the item value of 2), and so on.

Here’s a demo.

2. Combining multiple array methods into Array.map() and Array.filter() into a single step

Imagine you had an array of wizards at Hogwarts.

var wizards = [
  {
    name: 'Harry Potter',
    house: 'Gryfindor'
  },
  {
    name: 'Cedric Diggory',
    house: 'Hufflepuff'
  },
  {
    name: 'Tonks',
    house: 'Hufflepuff'
  },
  {
    name: 'Ronald Weasley',
    house: 'Gryfindor'
  },
  {
    name: 'Hermione Granger',
    house: 'Gryfindor'
  }
];

You want to create a new array that contains just the names of wizards who are in Hufflepuff. One way you could do that is by using the Array.filter() method to get back just wizards whose house property is Hufflepuff. Then, you’d use the Array.map() method to create a new array containing just the name property for the remaining wizards.

// Get the names of the wizards in Hufflepuff
var hufflepuff = wizards.filter(function (wizard) {
  return wizard.house === 'Hufflepuff';
}).map(function (wizard) {
  return wizard.name;
});

With the Array.reduce() method, we can get the same array in a single pass, improving our performance. You pass in an empty array ([]) as the starting value. On each pass, you check to see if the wizard.house is Hufflepuff. If it is, you push it to the newArr (our accumulator in this example). If not, you do nothing.

Either way, you return the newArr to become the accumulator on the next pass.

// Get the names of the wizards in Hufflepuff
var hufflepuff = wizards.reduce(function (newArr, wizard) {
  if (wizard.house === 'Hufflepuff') {
    newArr.push(wizard.name);
  }
  return newArr;
}, []);

Here’s another demo.

3. Creating markup from an array

What if, instead of creating an array of names, we wanted to create an unordered list of wizards in Hufflepuff? Instead of passing an empty array into Array.reduce() as our starting value, we’ll pass in an empty string ('') and call it html.

If the wizard.house equals Hufflepuff, we’ll concatenate our html string with the wizard.name wrapped in an opening and closing list item (li). Then, we’ll return the html to become the accumulator on the next loop.

// Create a list of wizards in Hufflepuff
var hufflepuffList = wizards.reduce(function (html, wizard) {
  if (wizard.house === 'Hufflepuff') {
    html += '<li>' + wizard.name + '</li>';
  }
  return html;
}, '');

Add an opening and closing unordered list element before and after Array.reduce(), and you’re ready to inject your markup string into the DOM.

// Create a list of wizards in Hufflepuff
var hufflepuffList = '<ul>' + wizards.reduce(function (html, wizard) {
  if (wizard.house === 'Hufflepuff') {
    html += '<li>' + wizard.name + '</li>';
  }
  return html;
}, '') + '</ul>';

See it in action here.

4. Grouping similar items in an array together

The lodash library has a groupBy() method takes a collection of items as an array and groups them together into an object based on some criteria.

Let’s say you want an array of numbers.

If you wanted to group all of the items in numbers together based on their integer value, you would do this with lodash.

var numbers = [6.1, 4.2, 6.3];

// returns {'4': [4.2], '6': [6.1, 6.3]}
_.groupBy(numbers, Math.floor);

If you had an array of words, and you wanted to group the items in words by their length, you would do this.

var words = ['one', 'two', 'three'];

// returns {'3': ['one', 'two'], '5': ['three']}
_.groupBy(words, 'length');

Creating a groupBy() function with Array.reduce()

You can recreate that same functionality using the Array.reduce() method.

We’ll create a helper function, groupBy(), that accepts the array and criteria to sort by as arguments. Inside groupBy(), we’ll run Array.reduce() on our array, passing in an empty object ({}) as our starting point, and return the result.

var groupBy = function (arr, criteria) {
  return arr.reduce(function (obj, item) {
    // Some code will go here...
  }, {});
};

Inside the Array.reduce() callback function, we’ll check to see if the criteria is a function, or a property of the item. Then we’ll get its value from the current item.

If there’s no property in the obj with that value yet, we’ll create it and assign an empty array as its value. Finally, we’ll push the item to that key, and return the object as the accumulator for the next loop.

var groupBy = function (arr, criteria) {
  return arr.reduce(function (obj, item) {

    // Check if the criteria is a function to run on the item or a property of it
    var key = typeof criteria === 'function' ? criteria(item) : item[criteria];

    // If the key doesn't exist yet, create it
    if (!obj.hasOwnProperty(key)) {
      obj[key] = [];
    }

    // Push the value to the object
    obj[key].push(item);

    // Return the object to the next item in the loop
    return obj;

  }, {});
};

Here’s a demo of the completed helper function.

Special thanks to Tom Bremer for helping me make some improvements to this one. You can find this helper function and more like it on the Vanilla JS Toolkit.

5. Combining data from two sources into an array

Remember our array of wizards?

var wizards = [
  {
    name: 'Harry Potter',
    house: 'Gryfindor'
  },
  {
    name: 'Cedric Diggory',
    house: 'Hufflepuff'
  },
  {
    name: 'Tonks',
    house: 'Hufflepuff'
  },
  {
    name: 'Ronald Weasley',
    house: 'Gryfindor'
  },
  {
    name: 'Hermione Granger',
    house: 'Gryfindor'
  }
];

What if you had another data set, an object of house points each wizard has earned.

var points = {
  HarryPotter: 500,
  CedricDiggory: 750,
  RonaldWeasley: 100,
  HermioneGranger: 1270
};

Imagine you wanted to combine both sets of data into a single array, with the number of points added to each wizard’s data in the wizards array. How would you do it?

The Array.reduce() method is perfect for this!

var wizardsWithPoints = wizards.reduce(function (arr, wizard) {

  // Get the key for the points object by removing spaces from the wizard's name
  var key = wizard.name.replace(' ', '');

  // If the wizard has points, add them
  // Otherwise, set them to 0
  if (points[key]) {
    wizard.points = points[key];
  } else {
    wizard.points = 0;
  }

  // Push the wizard object to the new array
  arr.push(wizard);

  // Return the array
  return arr;

}, []);

Here’s a demo combining data from two sources into an array.

6. Combining data from two sources into an object

What if you instead wanted to combine the two data sources into an object, where each wizard’s name was the key, and their house and points were properties? Again, the Array.reduce() method is perfect for this.

var wizardsAsAnObject = wizards.reduce(function (obj, wizard) {

  // Get the key for the points object by removing spaces from the wizard's name
  var key = wizard.name.replace(' ', '');

  // If the wizard has points, add them
  // Otherwise, set them to 0
  if (points[key]) {
    wizard.points = points[key];
  } else {
    wizard.points = 0;
  }

  // Remove the name property
  delete wizard.name;

  // Add wizard data to the new object
  obj[key] = wizard;

  // Return the array
  return obj;

}, {});

Here’s a demo combining two data sets into an object.

Should you use Array.reduce() more?

The Array.reduce() method has gone from being something I thought was pointless to my favorite JavaScript method. So, should you use it? And when?

The Array.reduce() method has fantastic browser support. It works in all modern browsers, and IE9 and above. It’s been supported in mobile browsers for a long time, too. If you need to go back even further than that, you can add a polyfill to push support back to IE6.

The biggest complaint you can make about Array.reduce() is that it’s confusing for people who have never encountered it before. Combining Array.filter() with Array.map() is slower to run and involves extra steps, but it’s easier to read. It’s obvious from the names of the methods what they’re supposed to be doing.

That said, there are times where Array.reduce() makes things that would be complicated more simple rather than more complicated. The groupBy() helper function is a good example.

Ultimately, this is another tool to add to your toolkit. A tool that, if used right, can give you super powers.


About the author

Chris Ferdinandi helps people learn vanilla JavaScript. He believes there’s a simpler, more resilient way to make things for the web.

Chris is the author of the Vanilla JS Pocket Guide series, creator of the Vanilla JS Academy training program, and host of the Vanilla JS Podcast. His developer tips newsletter is read by thousands of developers each weekday.

He’s taught developers at organizations like Chobani and the Boston Globe, and his JavaScript plugins have been used used by Apple and Harvard Business School. Chris Coyier, the founder of CSS-Tricks and CodePen, has described his writing as “infinitely quote-worthy.”

Chris loves pirates, puppies, and Pixar movies, and lives near horse farms in rural Massachusetts. He runs Go Make Things with Bailey Puppy, a lab-mix from Tennessee.

More articles by Chris