Web Standards

The Front-End Checklist is just a tool… everything depends on you.

Css Tricks - Thu, 11/30/2017 - 11:41am

One month ago, I launched the Front-End Checklist on GitHub. In less than 2 weeks, more than 10,000 people around the world starred the repository. That was completely unexpected and incredible!

I've been working as a front-end developer since 2011, but I started to build websites in 2000. Since then, like us all, I've been trying to improve the quality of my code and deliver websites faster. Along the way, I've been managing developers from two different countries. That has helped me to produce a checklist a little different than what I've found on around the web over the years.

While I was creating the checklist, I continuously had the book "The Checklist Manifesto: How to Get Things Right" by Atul Gawade in mind. That book has helped me build checklists for my work and personal life, and simplify things that sometimes seem too complex.

amzn_assoc_tracking_id = "csstricks-20"; amzn_assoc_ad_mode = "manual"; amzn_assoc_ad_type = "smart"; amzn_assoc_marketplace = "amazon"; amzn_assoc_region = "US"; amzn_assoc_design = "enhanced_links"; amzn_assoc_asins = "0312430000"; amzn_assoc_placement = "adunit"; amzn_assoc_linkid = "bc96260be7adede1459bf758a120d189";

If you are working alone or in a team, individually, remotely, or on-site, I wanted to share some advice on using the Front-End Checklist and the web application that goes with it. Perhaps I can convince you to integrate it into your development cycle.

#1 Decide which rules your project and team need to follow

Every project is different. Before starting a new project, the whole team (i.e. the project managers, designers, developers, QA, etc.) need to agree on what the deliverables will be.

To help you to decide, I created 3 different levels of priority: high, medium, and low. You don't necessarily need to agree with those distinctions, but they may help order your tasks.

The Front-End Checklist app was done to facilitate the creation of personalized checklists. Change some JSON files to your liking and you are ready to start!

#2 Define the rules to check at beginning, during, and at the end of your project

You shouldn't check all these rules only at the end of a project. You know as well as I do how projects are at the very end! Too hectic. Most of the items of the Front-End Checklist can be considered at the beginning of your development. It's up to you to decide. Make it clear to your team upfront what happens when.

#3 Learn a little more about each rules

Who loves reading the docs? Not most of us, but it's essential. If you want to understand the reasons for the rule, you can't avoid reading up about them. The more you understand the why of each rule, the better developer you become.

#4 Start to check!

The Front-End Checklist app can facilitate your life as a developer. It's a live checklist, so as you complete items your progress and grade are updated live. Everything is saved in localStorage so you can leave and come back as needed.

The project is open source, so feel free to fork it and use it however you like. I'm working on making sure all the files are commented. I especially invite those interested in Pug to take a look at the views folder.

#5 Integrate automated testing in your workflow

We all dream of automation (or is it just me?). For now, the Front-End Checklist is just an interactive list, but some of the tasks can be automated in your workflow.

Take a look at the gulpfile used to generate the project. All tasks are packages you can use with npm, webpack, etc.

#6 Validate every pages before sending to QA team and to production

If you're passionate about generating clean code and care about your code quality, you should be regularly testing your pages. It's so easy to make mistakes and remove some essential code. Or, someone else on your team might have done it, but it's your shared responsibilty to be catching things like that.

The Front-End Checklist can generate beautiful reports you can send to a project manager or Quality Assurance team.

#7 Enjoy your work above all

Some people might look at such a long checklist and feel sick to their stomach. Going through such a list might cause anxiety and really not be any fun.

But the Front-End Checklist is just a tool to help you deliver higher quality code. Code that affects all aspects of a project: the SEO, the user experience, the ROI, and ultimately the success of the project. A tool that can help across all those things might actually help reduce your anxiety and improve your health!

Conclusion

The success the Front-End Checklist received in such a short time reminded me that a lot of people are really interested in finding ways to improve their work. But just because the tool exists doesn't directly help with that. You also need to commit to using it.

In a time where AI is taking over many manual tasks, quality is a must-have. Even if automation takes over a lot of our tasks, some level of quality will remain impossible to automate, and us front-end developers still have many long days to enjoy our jobs.

The Front-End Checklist is just a tool… everything depends on you. is a post from CSS-Tricks

?7 Days of Free Stock Images

Css Tricks - Thu, 11/30/2017 - 8:12am

(This is a sponsored post.)

Storyblocks is exploding with over 400,000 stock photos, vectors, backgrounds and more! With its user friendly site, massive library to choose from, and fresh new content, there’s no stopping what you can do. All of the content is 100% free from any royalties. Anything you download is yours to keep and use forever! Right now you can get 7 days of free downloads. Get up to 20 photos, icons, and vectors everyday for 7 days. That's 140 downloads free over the course of the 7 days. Click on over and see where your imagination takes you! Start downloading now.

Direct Link to ArticlePermalink

?7 Days of Free Stock Images is a post from CSS-Tricks

Localisation and Translation on the Web

Css Tricks - Wed, 11/29/2017 - 5:56pm

The other day Chris wrote about how the CodePen team added lang='en' to the html element in all pens for accessibility reasons and I thought it was pretty interesting but I suddenly wanted to learn more about that attribute because I’ve never designed a website in any other language besides English and it might be useful for the future.

As if by magic Ire Aderinokun published this piece on Localisation and Translation on the Web just a couple of days later and thankfully it answers all those questions I had:

Coming from the English-speaking world, it can be easy to maintain the bubble that is the English-speaking World Wide Web. But in fact, more than half of web pages are written in languages other than English.

Since starting work at eyeo, I’ve had to think a lot more about localisation and translations because most of our websites are translated into several languages, something I previously didn’t have to really consider before. Once you decide to translate a web page, there are many things to take into account, and a lot of them I've found are useful even if your website is written in only one language.

I had no idea about the experimental, and currently unsupported, translate attribute or the mysterious margin-inline-start CSS property. Handy stuff!

Direct Link to ArticlePermalink

Localisation and Translation on the Web is a post from CSS-Tricks

Fontastic Web Performance

Css Tricks - Wed, 11/29/2017 - 5:54pm

In this talk Monica Dinculescu takes a deep dive into webfonts and how the font-display CSS property lets us control the way those fonts are rendered. She argues that there’s all sorts of huge performance gains to be had if we just spend a little bit of time thinking about the total number of fonts we load and how they’re loaded.

Also, Monica made a handy demo that gives an even more detailed series of examples of how the font-display property works:

This depends a lot on how you are using your webfont, and whether rendering the text in a fallback font makes sense. For example, if you're rendering the main body text on a site, you should use font-display:optional. On browsers that implement it, like Chrome, the experience will be much nicer: your users will get fast content, and if the web font download takes too long, they won't get a page relayout halfway through reading your article.

If you're using a web font for icons, there is no acceptable fallback font you can render these icons in (unless you're using emoji or something), so your only option is to completely block until the font is ready, with font-display:block.

Direct Link to ArticlePermalink

Fontastic Web Performance is a post from CSS-Tricks

WordPress + React

Css Tricks - Wed, 11/29/2017 - 9:58am

I posted just 2 months ago about Foxhound and how I found it pretty cool, but also curious that it was one of very few themes around that combine the WordPress JSON API and React, even though they seem like a perfect natural fit. Like a headless CMS, almost.

Since then, a few more things have crossed my desk of people doing more with this idea and combination.

Maxime Laboissonniere wrote Strapping React.js on a WordPress Backend: WP REST API Example:

I'll use WordPress as a backend, and WordPress REST API to feed data into a simple React e-commerce SPA:

  • Creating products with the WP Advanced Custom Fields plugin
  • Mapping custom fields to JSON payload
  • Consuming the JSON REST API with React
  • Rendering products in our store

Perhaps more directly usable, Postlight have put out a Starter Kit. Gina Trapani:

People who publish on the web love WordPress. Engineers love React. With some research, configuration, and trial and error, you can have both?—?but we’d like to save you the work.

Here's that repo.

Direct Link to ArticlePermalink

WordPress + React is a post from CSS-Tricks

V6: Typography and Proportions

Css Tricks - Tue, 11/28/2017 - 12:56pm

Here’s a good ol’ fashion blog post by Rob Weychert where he looks into the new design system that he implemented on his personal website and specifically the typographic system that ties everything together:

According to the OED, a scale is “a graduated range of values forming a standard system for measuring or grading something.” A piece of music using a particular scale—a limited selection of notes with a shared mathematic relationship—can effect a certain emotional tenor. Want to write a sad song? Use a minor scale. Changed your mind? Switch to a major scale and suddenly that same song is in a much better mood.

Spatial relationships can likewise achieve a certain visual harmony using similar principles, and the constraints a scale provides take a lot of the arbitrary guesswork out of the process of arranging elements in space. Most of what I design that incorporates type has a typographic scale as its foundation, which informs the typeface choices and layout proportions. The process of creating that scale begins by asking what the type needs to do, and what role contrasting sizes will play in that.

Direct Link to ArticlePermalink

V6: Typography and Proportions is a post from CSS-Tricks

An Idea for a Simple Responsive Spreadsheet

Css Tricks - Tue, 11/28/2017 - 9:02am

How do you make a spreadsheet-like interface responsive without the use of any JavaScript? This is the question I've been asking myself all week as I've been working on a new project and trying to figure out how to make the simplest spreadsheet possible. I wanted to avoid using a framework and instead, I decided to experiment with some new properties in order to use nothing but a light touch of CSS.

Spoilers! This is what I've come up with so far (oh and please note that this demo currently works in the latest version of Chrome). Try scrolling around a little bit:

See the Pen A Simple Responsive Spreadsheet – Final by Robin Rendle (@robinrendle) on CodePen.

Notice how the first column sticks to the left and the heading sticks to the top of the spreadsheet? This lets us scan lots of data without having to keep scrolling to figure out which column or row we're in — in a lot of interfaces like this it's pretty easy to get lost.

So how did I go about making this thing? Let's jump in!

Adding the markup

First we need to add our markup for the table and, just to make sure that this example is as realistic as possible, we're going to add a lot of rows and columns here:

See the Pen A Simple Responsive Spreadsheet – 1st by Robin Rendle (@robinrendle) on CodePen.

There's nothing really complex going on. We just have a regular ol' table with a <thead> and a <tbody>, but we do wrap the whole table in the table-wrapper div which I'll explain in just a little bit.

Next, we'll add basic styling to that wrapper element to move it into the center of the page and also give it a max-width. We also need to make sure that the .table-wrapper has overflow set to scroll, although at larger screen sizes we won't need that just yet:

body { display: flex; font-family: -apple-system; font-size: 90%; color: #333; justify-content: center; } .table-wrapper { max-width: 700px; overflow: scroll; }

See the Pen A Simple Responsive Spreadsheet – 2nd by Robin Rendle (@robinrendle) on CodePen.

Nifty! Now we can add styles for the first column of our table and the thead element as well as basic styling for each of the table cells:

table { border: 1px solid #ddd; border-collapse: collapse; } td, th { white-space: nowrap; border: 1px solid #ddd; padding: 20px; }

See the Pen A Simple Responsive Spreadsheet – 3 by Robin Rendle (@robinrendle) on CodePen.

The problem here is that we've now made a pretty inaccessible table; although we can scroll around in the spreadsheet we can't read which column or row is associated to which bit of data. This can lead to a table that is almost completely illegible and if we were to populate this with real data then it would be even worse:

position: sticky to the rescue!

position: sticky is a wonderfully handy CSS trick that I've started experimenting with a great deal lately. It lets you stick child elements to their parent containers so that as you scroll around the child element is always visible. And this is exactly what we need here for the first column and the heading of our table element.

We can use this relatively new feature with CSS like this:

// The heading of our table th { background-color: #eee; position: sticky; top: -1px; z-index: 2; // The first cell that lives in the top left of our spreadsheet &:first-of-type { left: 0; z-index: 3; } } // The first column that we want to stick to the left tbody tr td:first-of-type { background-color: #eee; position: sticky; left: -1px; z-index: 1; }

This z-index values are important here because we want the header to overlap the first left hand column that will also be sticky. However! We also want that empty cell at the top left to overlap both our header and our left hand column, like this:

See the Pen A Simple Responsive Spreadsheet – Final by Robin Rendle (@robinrendle) on CodePen.

But there we have it! A simple responsive spreadsheet where you can view both the heading and the first column no matter where you are in the table. Although, it's worth noting that your mileage may vary. position: sticky has relatively patchy support right now and so it's worth thoroughly testing before you start using it. Or you could use something like Stickybits that would act as a lightweight polyfill.

Also, if you need to dig into tables in more depth then we've made a rather handy Complete Guide to the Table Element.

An Idea for a Simple Responsive Spreadsheet is a post from CSS-Tricks

Introducing minmax()

Css Tricks - Tue, 11/28/2017 - 9:00am

It’s relatively easy to get lost in all the new features of CSS Grid because there’s just so much to learn and familiarize ourselves with; it’s much easier to learn it chunk by chunk in my opinion.

And so you might already be familiar with Rachel Andrew’s Grid By Example which contains a whole bunch of tutorials with new layout tips and tricks about CSS Grid. But the minmax() tutorial is one small chunk of Grid that you can learn today and thankfully Rachel has made a rather handy two minute long video that dives straight into it.

In fact, it’s pretty darn impressive how many opportunities just one new CSS feature can give us.

Direct Link to ArticlePermalink

Introducing minmax() is a post from CSS-Tricks

Animating Layouts with the FLIP Technique

Css Tricks - Mon, 11/27/2017 - 1:41pm

User interfaces are most effective when they are intuitive and easily understandable to the user. Animation plays a major role in this - as Nick Babich said, animation brings user interfaces to life. However, adding meaningful transitions and micro-interactions is often an afterthought, or something that is "nice to have" if time permits. All too often, we experience web apps that simply "jump" from view to view without giving the user time to process what just happened in the current context.

This leads to unintuitive user experiences, but we can do better, by avoiding "jump cuts" and "teleportation" in creating UIs. After all, what's more natural than real life, where nothing teleports (except maybe car keys), and everything you interact with moves with natural motion?

In this article, we'll explore a technique called "FLIP" that can be used to animate the positions and dimensions of any DOM element in a performant manner, regardless of how their layout is calculated or rendered (e.g., height, width, floats, absolute positioning, transform, flexbox, grid, etc.)

Why the FLIP technique?

Have you ever tried to animate height, width, top, left, or any other properties besides transform and opacity? You might have noticed that the animations look a bit janky, and there's a reason for that. When any property that triggers layout changes (such as `height`), the browser has to recursively check if any other element's layout has changed as a result, and that can be expensive. If that calculation takes longer than one animation frame (around 16.7 milliseconds), then the animation frame will be skipped, resulting in "jank" since that frame wasn't rendered in time. In Paul Lewis' article "Pixels are Expensive", he goes further in depth at how pixels are rendered and the various performance expenses.

In short, our goal is to be short - we want to calculate the least amount of style changes necessary, as quickly as possible. The key to this is only animating transform and opacity, and FLIP explains how we can simulate layout changes using only transform.

What is FLIP?

FLIP is a mnemonic device and technique first coined by Paul Lewis, which stands for First, Last, Invert, Play. His article contains an excellent explanation of the technique, but I'll outline it here:

  • First: before anything happens, record the current (i.e., first) position and dimensions of the element that will transition. You can use element.getBoundingClientRect() for this, as will be shown below.
  • Last: execute the code that causes the transition to instantaneously happen, and record the final (i.e., last) position and dimensions of the element.*
  • Invert: since the element is in the last position, we want to create the illusion that it's in the first position, by using transform to modify its position and dimensions. This takes a little math, but it's not too difficult.
  • Play: with the element inverted (and pretending to be in the first position), we can move it back to its last position by setting its transform to none.

Below is how these steps can be implemented with the Web Animations API:

const elm = document.querySelector('.some-element'); // First: get the current bounds const first = elm.getBoundingClientRect(); // execute the script that causes layout change doSomething(); // Last: get the final bounds const last = elm.getBoundingClientRect(); // Invert: determine the delta between the // first and last bounds to invert the element const deltaX = first.left - last.left; const deltaY = first.top - last.top; const deltaW = first.width / last.width; const deltaH = first.height / last.height; // Play: animate the final element from its first bounds // to its last bounds (which is no transform) elm.animate([{ transformOrigin: 'top left', transform: ` translate(${deltaX}px, ${deltaY}px) scale(${deltaW}, ${deltaH}) ` }, { transformOrigin: 'top left', transform: 'none' }], { duration: 300, easing: 'ease-in-out', fill: 'both' });

Note: At the time of writing, the Web Animations API is not yet supported in all browsers. However, you can use a polyfill.

See the Pen How the FLIP technique works by David Khourshid (@davidkpiano) on CodePen.

There are two important things to note:

  1. If the element's size changed, you can transform scale in order to "resize" it with no performance penalty; however, make sure to set transformOrigin to 'top left' since that's where we based our delta calculations.
  2. We're using the Web Animations API to animate the element here, but you're free to use any other animation engine, such as GSAP, Anime, Velocity, Just-Animate, Mo.js and more.
Shared Element Transitions

One common use-case for transitioning an element between app views and states is that the final element might not be the same DOM element as the initial element. In Android, this is similar to a shared element transition, except that the element isn't "recycled" from view to view in the DOM as it is on Android.
Nevertheless, we can still achieve the FLIP transition with a little magic illusion:

const firstElm = document.querySelector('.first-element'); // First: get the bounds and then hide the element (if necessary) const first = firstElm.getBoundingClientRect(); firstElm.style.setProperty('visibility', 'hidden'); // execute the script that causes view change doSomething(); // Last: get the bounds of the element that just appeared const lastElm = document.querySelector('.last-element'); const last = lastElm.getBoundingClientRect(); // continue with the other steps, just as before. // remember: you're animating the lastElm, not the firstElm.

Below is an example of how two completely disparate elements can appear to be the same element using shared element transitions. Click one of the pictures to see the effect.

See the Pen FLIP example with WAAPI by David Khourshid (@davidkpiano) on CodePen.

Parent-Child Transitions

With the previous implementations, the element bounds are based on the window. For most use cases, this is fine, but consider this scenario:

  • An element changes position and needs to transition.
  • That element contains a child element, which itself needs to transition to a different position inside the parent.

Since the previously calculated bounds are relative to the window, our calculations for the child element are going to be off. To solve this, we need to ensure that the bounds are calculated relative to the parent element instead:

const parentElm = document.querySelector('.parent'); const childElm = document.querySelector('.parent > .child'); // First: parent and child const parentFirst = parentElm.getBoundingClientRect(); const childFirst = childElm.getBoundingClientRect(); doSomething(); // Last: parent and child const parentLast = parentElm.getBoundingClientRect(); const childLast = childElm.getBoundingClientRect(); // Invert: parent const parentDeltaX = parentFirst.left - parentLast.left; const parentDeltaY = parentFirst.top - parentLast.top; // Invert: child relative to parent const childDeltaX = (childFirst.left - parentFirst.left) - (childLast.left - parentLast.left); const childDeltaY = (childFirst.top - parentFirst.top) - (childLast.top - parentLast.top); // Play: using the WAAPI parentElm.animate([ { transform: `translate(${parentDeltaX}px, ${parentDeltaY}px)` }, { transform: 'none' } ], { duration: 300, easing: 'ease-in-out' }); childElm.animate([ { transform: `translate(${childDeltaX}px, ${childDeltaY}px)` }, { transform: 'none' } ], { duration: 300, easing: 'ease-in-out' });

A few things to note here, as well:

  1. The timing options for the parent and child (duration, easing, etc.) do not necessarily need to match with this technique. Feel free to be creative!
  2. Changing dimensions in parent and/or child (width, height) was purposefully omitted in this example, since it is an advanced and complex topic. Let's save that for another tutorial.
  3. You can combine the shared element and parent-child techniques for greater flexibility.
Using Flipping.js for Full Flexibility

The above techniques might seem straightforward, but they can get quite tedious to code once you have to keep track of multiple elements transitioning. Android eases this burden by:

  • baking shared element transitions into the core SDK
  • allowing developers to identify which elements are shared by using a common android:transitionName XML attribute

I've created a small library called Flipping.js with the same idea in mind. By adding a data-flip-key="..." attribute to HTML elements, it's possible to predictably and efficiently keep track of elements that might change position and dimensions from state to state.

For example, consider this initial view:

<section class="gallery"> <div class="photo-1" data-flip-key="photo-1"> <img src="/photo-1"/> </div> <div class="photo-2" data-flip-key="photo-2"> <img src="/photo-2"/> </div> <div class="photo-3" data-flip-key="photo-3"> <img src="/photo-3"/> </div> </section>

And this separate detail view:

<section class="details"> <div class="photo" data-flip-key="photo-1"> <img src="/photo-1"/> </div> <p class="description"> Lorem ipsum dolor sit amet... </section>

Notice in the above example that there are 2 elements with the same data-flip-key="photo-1". Flipping.js tracks the "active" element by choosing the first element that meet these criteria:

  • The element exists in the DOM (i.e., it hasn't been removed or detached)
  • The element is not hidden (hint: elm.getBoundingClientRect() will have { width: 0, height: 0 } for hidden elements)
  • Any custom logic specified in the selectActive option.
Getting Started with Flipping.js

There's a few different packages for Flipping, depending on your needs:

  • flipping.js: tiny and low-level; only emits events when element bounds change
  • flipping.web.js: uses WAAPI to animate transitions
  • flipping.gsap.js: uses GSAP to animate transitions
  • More adapters coming soon!

You can grab the minified code directly from unpkg:

Or you can npm install flipping --save and import it into your projects:

// import not necessary when including the unpkg scripts in a <script src="..."> tag import Flipping from 'flipping/adapters/web'; const flipping = new Flipping(); // First: let Flipping read all initial bounds flipping.read(); // execute the change that causes any elements to change bounds doSomething(); // Last, Invert, Play: the flip() method does it all flipping.flip();

Handling FLIP transitions as a result of a function call is such a common pattern, that the .wrap(fn) method transparently wraps (or "decorates") the given function by first calling .read(), then getting the return value of the function, then calling .flip(), then returning the return value. This leads to much less code:

const flipping = new Flipping(); const flippingDoSomething = flipping.wrap(doSomething); // anytime this is called, FLIP will animate changed elements flippingDoSomething();

Here is an example of using flipping.wrap() to easily achieve the shifting letters effect. Click anywhere to see the effect.

See the Pen Flipping Birthstones #Codevember by David Khourshid (@davidkpiano) on CodePen.

Adding Flipping.js to Existing Projects

In another article, we created a simple React gallery app using finite state machines. It works just as expected, but the UI could use some smooth transitions between states to prevent "jumping" and improve the user experience. Let's add Flipping.js into our React app to accomplish this. (Keep in mind, Flipping.js is framework-agnostic.)

Step 1: Initialize Flipping.js

The Flipping instance will live on the React component itself, so that it's isolated to only changes that occur within that component. Initialize Flipping.js by setting it up in the componentDidMount lifecycle hook:

componentDidMount() { const { node } = this; if (!node) return; this.flipping = new Flipping({ parentElement: node }); // initialize flipping with the initial bounds this.flipping.read(); }

By specifying parentElement: node, we're telling Flipping to only look for elements with a data-flip-key in the rendered App, instead of the entire document.
Then, modify the HTML elements with the data-flip-key attribute (similar to React's key prop) to identify unique and "shared" elements:

renderGallery(state) { return ( <section className="ui-items" data-state={state}> {this.state.items.map((item, i) => <img src={item.media.m} className="ui-item" style={{'--i': i}} key={item.link} onClick={() => this.transition({ type: 'SELECT_PHOTO', item })} data-flip-key={item.link} /> )} </section> ); } renderPhoto(state) { if (state !== 'photo') return; return ( <section className="ui-photo-detail" onClick={() => this.transition({ type: 'EXIT_PHOTO' })}> <img src={this.state.photo.media.m} className="ui-photo" data-flip-key={this.state.photo.link} /> </section> ) }

Notice how the img.ui-item and img.ui-photo are represented by data-flip-key={item.link} and data-flip-key={this.state.photo.link} respectively: when the user clicks on an img.ui-item, that item is set to this.state.photo, so the .link values will be equal.

And since they are equal, Flipping will smoothly transition from the img.ui-item thumbnail to the larger img.ui-photo.

Now we need to do two more things:

  1. call this.flipping.read() whenever the component will update
  2. call this.flipping.flip() whenever the component did update

Some of you might have already guessed where these method calls are going to occur: componentWillUpdate and componentDidUpdate, respectively:

componentWillUpdate() { this.flipping.read(); } componentDidUpdate() { this.flipping.flip(); }

And, just like that, if you're using a Flipping adapter (such as flipping.web.js or flipping.gsap.js), Flipping will keep track of all elements with a [data-flip-key] and smoothly transition them to their new bounds whenever they change. Here is the final result:

See the Pen FLIPping Gallery App by David Khourshid (@davidkpiano) on CodePen.

If you would rather implement custom animations yourself, you can use flipping.js as a simple event emitter. Read the documentation for more advanced use-cases.

Flipping.js and its adapters handle the shared element and parent-child transitions by default, as well as:

  • interrupted transitions (in adapters)
  • enter/move/leave states
  • plugin support for plugins such as mirror, which allows newly entered elements to "mirror" another element's movement
  • and more planned in the future!
Resources

Similar libraries include:

  • FlipJS by Paul Lewis himself, which handles simple single-element FLIP transitions
  • React-Flip-Move, a useful React library by Josh Comeau
  • BarbaJS, not necessarily a FLIP library, but one that allows you to add smooth transitions between different URLs, without page jumps.

Further resources:

Animating Layouts with the FLIP Technique is a post from CSS-Tricks

Netflix functions without client-side React, and it’s a good thing

Css Tricks - Mon, 11/27/2017 - 10:18am

Recently Netflix removed client-side React from their landing page which caused a bit of a stir. So Jake Archibald investigated why the team did that and how it’s actually a good thing for the React community in the long term:

When the PS4 was released in 2013, one of its advertised features was progressive downloading – allowing gamers to start playing a game while it's downloading. Although this was a breakthrough for consoles, the web has been doing this for 20 years. The HTML spec (warning: 8mb document), despite its size, starts rendering once ~20k is fetched.

Unfortunately, it's a feature we often engineer-away with single page apps, by channelling everything through a medium that isn't streaming-friendly, such as a large JS bundle.

I like the whole vibe of this post because it suggests that we should be careful when we pick our tools; we only should pick the right tool for the right job, instead of treating every issue as if it needs a giant hammer made of JavaScript. Also! Burke Holland wrote a funny piece last week on this topic with some of his thoughts.

Direct Link to ArticlePermalink

Netflix functions without client-side React, and it’s a good thing is a post from CSS-Tricks

Apps Have Command Prompts Now

Css Tricks - Mon, 11/27/2017 - 8:43am

Command lines were an early innovation in computers, and were the dominant way to interact with them in the 1960's - 80's. That gave way to GUIs for most users after that. I don't think we need to launch a scientific study to figure out why. Most users find it more comfortable and intuitive to accomplish things with interactive moments and visual feedback.

But command lines never went away. GUI's are generally a limited abstraction of what you could do through a command line anyway, so power users gravitate toward the closer-to-the-metal nature of the command line.

But we might be in the middle of a return to a happy medium.

Finder-ing

We know Apple is quite fond of cutting features. Particularly little-used features or power-user-only features. Curiously, this one has stuck around:

The "Go To Folder" dialog, via Command-Shift-G

William Pearson wrote:

If there’s only one keyboard shortcut you should remember in Mac OS X it’s this: Go To Folder. ... Is there a keyboard shortcut that is more useful than “Go To Folder”? I don’t think so.

I'm not sure about that, but it's clear some people take this shortcut pretty seriously! And yes, a keyboard shortcut, but one that essentially opens a command line prompt that can do one thing.

I guess that isn't terribly surprising, considering the success of apps like Alfred, which perhaps it's fair to say is a command line for finding, opening and doing things.

The Finder also has Spotlight (since OS X 10.4 Tiger anyway, 2005) which is largely a thing for search (especially these days, as it returns results the web as well).

Spotlight has a keyboard command (Command-Space) and then you just type to do stuff, so it's very much a command prompt. Just one that's pretty decked out in user-friendliness.

And while we're on this bend, we can't forget about Quicksilver. Interestingly, both Alfred and Quicksilver postdate Spotlight. I guess that speaks to Spotlight kind of sucking in the early days, and leaving people wanting more.

Code Editors

Most developers, I'm sure, are quite aware of the literal command line. Almost all the big development tools are command line based tools. Everything from Git to Gulp, image optimizers to package managers, Capistrano to webpack... they are all tools you use from the command line. If you have a GUI for any of them, it's probably a light abstraction over command line methods.

But, aside from the most hardcore of all Vim users who do all their code editing from a terminal window, we don't actually write code on the command line, but in an editor with a GUI.

Code Editors are a perfect breeding ground for ideas that combine the best of GUI's and command lines.

Let's look at Sublime Text. When creating a new folder, I might want to do that with the GUI. There I can see the existing folder structure and see exactly what I'm doing.

But say I want to jump to a file I know exists. Say it's buried a number of directories deep, and I'm glad that it is because it adheres to the structure of the current project. I might have to click - click - scroll - click - scroll - click to get there with a GUI, which isn't the greatest interaction.

Instead, I can fire up a command prompt in Sublime Text, in this case it's iconic Goto Anything command, type in something close to the file name, and find it.

Perhaps even more command-prompt-like is the literal Command Palette which is an extensible command-running menu triggered by a keyboard shortcut. Perhaps I want to run a specific Emmet command, correct syntax highlighting, or trigger an a find/replace extension to do its thing.

These things are in a similar boat as finding a file-in-a-haystack. There could be hundreds or thousands of commands. Your brain and typing fingers can find them quicker than your hand on a mouse in a UI can.

Sketch Runner

Sketch Runner is a popular plugin for Sketch that adds a command prompt to Sketch. Here's their product video:

If you think of elements and groups in a design document just like files in a code project, the "Jump anywhere" feature makes sense. It's just like "Goto Anything".

Perhaps your design document has hundreds of symbols. Your brain probably has a mental map of that that is quicker to navigate than moving your mouse through nested menus. Thus, a command prompt to type in the name (fuzzy search) and insert it.

Slack

Too many Slacks, amiright?

I don't think it would be terrible uncommon to have a dozen Slack teams, hundreds of channels, and thousands of people. Particularly if you're fond of joining "Public Slacks", like say the A11Y Slack.

Say I want to shoot a message to Sarah. I can open the Quick Switcher and just start typing her name and get there.

You have to be in the right Slack for names (or channels) to work, but you can get to the right slack via Quick Switcher and then do a new search.

Notion

Notion has a pretty awesome take on the command prompt. It's available everywhere you are in a document just by pressing the slash / key.

There are probably ~30 things you can do. The menu is nice, but being able to type what you mean quickly is even better.

In addition to searching the menu, you can just complete the word after the slash (a slash command) to do the thing.

Chrome DevTools

David Khourshid:

I've been using the command prompt in Chrome Dev Tools _so much more_ because opening the Animate tab takes like 17 clicks.

Yet another good use case!

So

There is a lot of apps doing interesting things here. I'm a fan of all of it!

Even more could probably benefit from it. Photoshop is notoriously complex, but a lot of us have familiarity with the things it can do. Seems like a perfect canidate for a fuzzy-search enabled command prompt!

Users might be able to take things into their own hands a bit here too. Alfred users could use the Menu Bar Search plugin which allows you to:

Search for and activate application menu items for the frontmost application. The workflow lists the menu items for the current application, filtering them by whatever is entered into Alfred.

Apps can easily have dozens of menu items, and this would make them all command prompt-able.

Standardization is also an interesting thing to consider. It seems some apps have followed each other. Command-Shift-P is the Sublime Text command runner, which was used by Chrome DevTools, and also by VS Code. I kinda like the Command-Space of Spotlight, but that doesn't mean web-based apps should copy it. In fact, it means they can't, because the OS would override it.

TL;DR

When UI is cumbersome or impractical, a command line makes good sense. Many apps benefit from offering both a UI and a command line, in various forms.

Apps Have Command Prompts Now is a post from CSS-Tricks

Editing the W3C HTML5 spec

Css Tricks - Fri, 11/24/2017 - 4:53am

Bruce Lawson has been tapped to co-edit the W3C HTML5 spec and, in his announcement post, clarified the difference between that and the WHATWG spec:

The WHATWG spec is a future-facing document; lots of ideas are incubated there. The W3C spec is a snapshot of what works interoperably – authors who don’t care much about what may or may not be round the corner, but who need solid advice on what works now may find this spec easier to use.

I was honestly unfamiliar with the WHATWG spec and now I find it super interesting to know there are two working groups pushing HTML forward in distinct but (somewhat) cooperative ways.

Kudos to you, Bruce! And, yes, Vive open standards!

Direct Link to ArticlePermalink

Editing the W3C HTML5 spec is a post from CSS-Tricks

On the Growing Popularity of Atomic CSS

Css Tricks - Fri, 11/24/2017 - 4:43am

Even if you consider yourself a CSS expert, chances are that at some point on a large project you've had to deal with a convoluted, labyrinthine stylesheet that never stops growing. Some stylesheets can feel like a messy entangled web of inheritance.

Spaghetti Monster

The cascade is incredibly powerful. Small changes can have large effects, making it harder to know what the immediate consequences will be. Refactoring, changing, and removing CSS is seen as risky and approached with trepidation as it's difficult to know all the places it's being used.

One thing that is often hard to articulate with new tooling is when, exactly do you start to reach for this? The answer is rarely (if ever) immediately and in all situations.

One of those situations, in my limited experience, is on large teams with large codebases. The feeling is that the CSS can get far too large and team members essentially become afraid of it, and the CSS becomes jokingly-but-accurately “append-only”.

Along comes a tool that delivers on a promise of shipping far less CSS and in a way that (after a learning curve) nobody is ever afraid of again… I can see the appeal.

- Chris Coyier

Atomic CSS keeps things simple

I no longer had to think about how to organise my CSS. I didn't have to think about what to name my 'components', where to draw the line between one component and another, what should live where, and crucially, how to refactor things when new requirements came in.

- Callum Jefferies, Takeaways from trying out Tachyons CSS after ages using BEM

Atomic CSS offers a straightforward, obvious, and simple methodology. Classes are immutable - they don't change. This makes the application of CSS predictable and reliable as classes will always do exactly the same thing. The scope of adding or removing a utility class in an HTML file is unambiguous, giving you the confidence that you aren't breaking anything else. This can reduce cognitive load and mental-overhead.

Naming components is notoriously difficult. Deciding on a class name that is both meaningful but also vague enough to be reusable is time-consuming and mentally taxing.

There are only two hard things in Computer Science: cache invalidation and naming things.

– Phil Karlton

Coming up with the appropriate abstractions is hard. Naming utility classes, by contrast, is completely straightforward.

/* naming utility classes */ .relative { position: relative; } .mt10 { margin-top: 10px; } .pb10 { padding-bottom: 10px; }

Atomic classes speak for themselves. Their intent and effect are immediately obvious. While littering HTML with countless classes may look cluttered, HTML is much easier to reason about than an impenetrably gargantuan and incomprehensible wall of tangled styles.

In a mixed-ability team, perhaps involving backend developers with limited interest and knowledge of CSS, there's less chance of people messing up the stylesheet.

Taken from ryanair.com - a whole load of CSS all doing one thing. Dealing with stylistic variation

Utility classes are perfect for dealing with small stylistic variations. While design systems and pattern libraries may be all the rage these days, what this approach recognizes is that there will continuously be new requirements and variations. All the talk about component reusability often isn't reflected in the design mocks that get passed your way. While visual and brand consistency is good, the wide variety of contexts on a large website make some variation inevitable and justified.

The Medium development team moved away from BEM modifiers, as documented on their blog.

What if we want a component to differ from another in only one single small way. If you've adopted a BEM naming convention, the modifier classes may well get out of hand - countless modifiers that often do only a single thing. Lets take margins as an example. The margins of a component are unlikely to remain universally consistent for a component. The desired spacing depends not only on the component but also its position on a page and its relation to its surrounding elements. Much of the time designs will contain similar but non-identical UI elements, which are arduous to deal with using traditional CSS.

A lot of people dislike it Aaron Gustafson, chief editor of A List Apart, former manager of the Web Standards Project, Microsoft employee. Mozilla Engineer Soledad Penades From the creator of CSS Zen Garden How is Atomic CSS different from inline styles?

This is the question always asked of atomic CSS by its critics. Inline styles have long been deemed a bad practice, rarely used since the early days of the web. Critics aren't completely wrong to equate atomic CSS to inline styles because they both suffer from the same major pain point. Here's an example: What if we want to change everything with a .black class to be navy instead? We could do this:

.black { color: navy; }

That's obviously a terrible idea.

Text editors are sophisticated things these days. It feels somewhat hazardous, but it would be simple enough to use find and replace to change all instances of the .black class with a new .navy class. The real problem is when you want to change only certain instances of .black to be .navy.

In traditional approaches to CSS, adjusting the styling of a component is as easy as updating a single value in a single class in a CSS file. With atomic CSS this becomes the tedious task of searching through every piece of HTML to update every instance of said component. However advanced code editors become, there's no getting around this. Even if you're separating your markup into reusable templates, this is still a major drawback. Perhaps this manual labour is worth it for the simplicity of this approach. Updating HTML files with different classes may be tedious but its not difficult. (Although there have been times when I have temporarily introduced stylistic inconsistency by missing certain instances of the relevant component when manually updating.) If a design changes, chances are you'll need to hand-edit classes from all over your HTML.

While atomic CSS shares inline styles big drawback, they aren't a retrograde step into the past. Utility classes are better than inline styles in all kinds of ways.

Atomic CSS vs. Inline Styles Atomic classes allow abstraction, inline styles don't

With atomic classes, it is possible to create abstractions that would be impossible with inline styles.

<p style="font-family: helvetica; color: rgb(20, 20, 20)"> Inline styles suck. </p> <p class="helvetica rgb202020"> Badly written CSS isn't very different. </p> <p class="sans-serif color-dark"> Utility classes allow for abstraction. </p>

The first two examples shown above would require a manual find-and-replace in order to update styling were the design to change. The styles in the third example can be adjusted in a single place within a stylesheet.

Tooling

Sass, Less, PostCSS, Autoprefixer… The CSS community has created a lot of useful tools that weren't available for inline styles.

Brevity

Rather than writing out verbose inline styles, atomic classes can be terse abbreviations of declarations. It's less typing: mt0 vs margin-top: 0, flex vs display: flex, etc.

Specificity

This is a contentious point. If a class or inline style only does one single thing, chances are you want it to do that thing. Some people have even advocated using !important on all utility classes to ensure they override everything else. Similarly, proponents of inline styles see its inability to be overridden (by anything other than !important) as a selling point - it means you can be sure the style will be applied. However, a class alone is specific enough to override any base style. The lower specificity of atomic classes compared to inline styles is a good thing. It allows more versatility. Were all used to changing classes on JavaScript to change styles. Inline styles make this harder.

Classes in stylesheets can do things inline styles can't

Inline styles do not support media queries, pseudo selectors, @supports, or CSS animations. Perhaps you have a single hover effect you want to apply to disparate elements rather than to only one component.

.circle { border-radius: 50%; } .hover-radius0:hover { border-radius: 0; }

Simple reusable media query rules can also be turned into a utility class. Its common to use a classname prefix for small, medium and large screen sizes. Here is an example of a flexbox class that will only apply on medium and large screen sizes:

@media (min-width: 600px) { .md-flex { display: flex; } }

This wouldn't be possible with an inline style.

Perhaps you want a reusable pseudo-content icon or label?

.with-icon::after { content: 'some icon goes here!'; } Limiting choice can be a good thing

Inline styles can be anything. This freedom could easily lead to design anarchy and inconsistency. By predefining classes for everything, atomic CSS can ensure a certain amount of stylistic consistency. Rather than ad libbing colours and values from an infinite amount of options, utility classes offer a curated set of predefined options. Developers choose from this limited set of single-purpose utility classes. This constraint can both eliminate the problem of an ever-growing stylesheet and maintain visual consistency.

Take the box-shadow as an example. An inline style will have an almost limitless amount of options for offset, spread, color, opacity and blur radius.

<div style="box-shadow: 2px 2px 2px rgba(10, 10, 250, .4)">stuff</div>

With an atomic approach, CSS authors can define the preferred style, which is then simply applied, without the possibility of stylistic inconsistency.

<div class="box-shadow">stuff</div> Atomic CSS is not all or nothing

There's no doubt that utility class frameworks like Tachyons have grown in popularity. However, CSS approaches are not mutually exclusive. There are plenty of cases where utility classes aren't the best option:

  • If you need to change a lot of styles for a particular component inside of a media query.
  • If you want to change multiple styles with JavaScript, it's easier to abstract that into a single class.

Utility classes can coexist with other approaches. Its probably a good idea to define base styles and sane defaults globally. If you keep duplicating the same long string of utility classes, chances are the styles should be abstracted into a single class. You can mix in component classes, but do so only when you know they will be reused.

Taking a component-first approach to CSS means you create components for things even if they will never get reused. This premature abstraction is the source of a lot of bloat and complexity in stylesheets.

- Adam Wathan

The smaller the unit, the more reusable it is.

- Thierry Koblentz

Looking at the newest release of Bootstrap, a whole host of utility classes is now offered, while still including its traditional components. Increasingly, popular frameworks are taking this mixed approach.

On the Growing Popularity of Atomic CSS is a post from CSS-Tricks

Save 15% or More on Car Insurance by Switching to Plain JavaScript

Css Tricks - Wed, 11/22/2017 - 6:34am

Satire disclaimer: This article is as much satire as it is serious insight if there is even any of that at all. Don’t take it too seriously, but do tell all your friends. Also, the bit about Taco Bell is 100% true. I wouldn’t joke about something like that.

My day usually begins like this:?I wake up at 6:15 a.m. (kill me) to get the kids ready for school. They’re mad. I’m mad. Everyone is on the brink of an emotional breakdown because it's 6:15 in the morning.

Usually the first thing that I do when I wake up is roll out of bed and start hammering out pushups like Christian Bale.

BWAHAHAHA. No.

Before I’m even fully awake and out of bed, I grab my phone and look at Twitter. It’s a sickness, I know. I’m not proud of it but at least I’m out here admitting that I have a problem and I believe according to the rules of science that fully negates my problem and makes me better than you.

One morning a few weeks ago I wake up to this tweet…

Removing client-side React.js (but keeping it on the server) resulted in a 50% performance improvement on our landing page pic.twitter.com/vM7JhWhYKu

— Netflix UI Engineers (@NetflixUIE) October 26, 2017

The wonderful thing about Twitter is that there is essentially zero context for anything you see, which means your crazy brain gets to fill in all the holes and, in my case, that’s a recipe for utter disaster.

Here is how I read this tweet….

Heavily doctored by me. My Photoshop skills are a huge embarrassing failure.

I believe my brain read it that way because that’s literally what the original tweet says. My brain just adds the “Your whole life is a lie” part to pretty much everything I read or hear.

Your Whole Life is a Lie

This immediately dumped me into an existential crisis.

To be fair, I’m almost constantly in a state of crisis so it’s not like this was a big leap for me. Just last night at Taco Bell I had to choose between the Beefy 5-layer Burrito and the Cheesy Gordita Crunch and I almost came apart in the drive through. You can’t force decisions like that on people and expect an immediate response! And why do I need 50 packets of Fire sauce!?!

The point is that I’m kind of emotionally fragile as it is, so you can’t suggest to me that you got rid of React because all of a sudden people just don’t need it anymore.

I had so, so, so many. questions like:

  • What about binding?
  • What about components?
  • What about state?
  • What about templates?

You’re telling me that all of a sudden you just don’t need any of that stuff anymore? One does not simply “move to plain JavaScript” by removing React from their project. If you actually did that you would just be moving from React to your own version of React. Facebook could say that their site is built in “plain JavaScript” too. They just decided to name some of that JavaScript “React" in the process.

It was nonsensical. You might as well have said that you saved 15% on car insurance by moving to plain JavaScript. Thankfully, I only had to wait 6 agonizing days before Jake Archibald took to the blogs to clear everything up.

&#x1f4dd; Netflix "removed" React and improved performance.
?? Despite appearances, this reflects well on React.https://t.co/R8SohrLX6q

— Jake Archibald (@jaffathecake) October 31, 2017

THIS IS NOT HELPING, JAKE! I’M LOSING IT OVER HERE!

The post goes on to explain that Netflix is actually deferring client-side React until it’s needed and going with server rendered React in the meantime. He also points out that it’s only logical that it would be faster because the browser is doing less work. Netflix is apparently loading client-side React in the background. It’s there when you need it, but you don’t have to parse it if you don’t.

I decided to check this out and see for myself what is going on.

Netflix Login

One of the places Jake mentions that server-side React is appropriate is on the login screen. So let’s start there. I loaded the login screen and it looks to me like client-side React is still every much in effect here.

As an aside, Netflix is great at naming things. I mean, look at these components—AkiraLayout, JawboneLinkProvider, FreezedWrapper? OK, FreezedWrapper isn’t that exciting but you can’t take AkiraLayout from me.

So I can’t find where React has been removed. The login page itself comes in at around 194KB and that’s before it loads the loginController.jsx file which bumps it up another 204KB.

I then did what I should have done the first time which is to watch the video from Netflix that was responsible for this descent into the depths of my insecurity and I noticed that they only mentioned the splash page.

The splash page is just netflix.com. No login. No videos. The splash page. That slide? The one that made it’s way all over the internet and into my therapy sessions? That slide is referring only to the splash page. Netflix did remove React from their splash page and replace the few interactions they had with plain JavaScript.

And there is your context. So let’s fix the slide again…

That is the actual story here.

It’s unfortunate that we latch on to a single slide taken completely out of context. This is not the fault of Netflix. Or maybe it is. I mean, they did tweet it out but, look, this is really the fault of 2017. This is how all of the news in our lives plays out.

What’s super unfortunate here, and what Jake was trying to convey in his post, is that we completely missed some actual cool things that Netflix is doing. Mainly the combination of server-side React and Prefetching. Or rather the idea that more complex code can be downloaded and parsed in the background instead of when the page loads.

Prefetching is Not a Solved Problem

We tend to forget that things like prefetching are not necessarily a solved problem. While Service Workers are awesome, Netflix can’t use them because the support is too sparse. Beyond that, the browser Prefetching API is flaky. In that same presentation, Netflix reports that the API (which is just the link tag) has a success rate as low as a 30%. That means your prefetch will only work about a third of the time in some cases. &#x1f633;

The reason for this is that the API is trying to make a bunch of decisions about whether or not it should prefetch depending on your device and resources. It’s not a guarantee that your resources will be loaded at all.

What’s most remarkable to me is that Netflix hit on another solution that is so simple it hurts: just make an AJAX call and don’t do anything with the result; the browser will cache that resource.

MY GOODNESS I LOVE THE WEB!

You Uh, Still Need React

So yes, you still need React on the client-side. Netflix is still using it and never said that they were not.

What they did say was that they had figured out some creative ways to make the experience better for the user and had combined that with their current React implementation. This should be exciting to you if you’re a React developer.

Maybe Netflix will open source some library for prefetching with a way cool name. Is "fakenews.js” taken?

Special Thanks to Brian Holt who reviewed this article and was still willing to be my friend.

Save 15% or More on Car Insurance by Switching to Plain JavaScript is a post from CSS-Tricks

Mutation Observer notes

QuirksBlog - Wed, 11/22/2017 - 4:59am

My current project requires me to use Mutation Observers, and I couldn’t resist the temptation to do a little fundamental research. Overall they work fine, but there is one tricky bit when it comes to text changes. Also, I found two Edge bugs.

My current client asked me to keep track of DOM nodes that appear onmouseover — and my script should work in pretty much any site. So we have add some information to DOM nodes that appear onmouseover, which will allow a later script to figure out that there was a mouseover involved. That’s obviously a job for Mutation Observers.

Here’s Microsoft’s documentation for Mutation Observers, which I find clearer than the MDN page.

Mutation Observers on mouseovers

So let’s get to work. This is the basic idea:

var mutationConfig = { childList: true, subtree: true, }; var observer = new MutationObserver(createRecords); document.addEventListener('mouseover',function (e) { observer.observe(document.documentElement,mutationConfig); },true); document.addEventListener('mouseover',function (e) { observer.disconnect(); },false); function createRecords() { // check if it's really a childList mutation // if so, add a few properties to the created DOM nodes }

I create a Mutation Observer for DOM nodes (though it also catches some text changes — I’ll get back to that). The observer observes the entire document because there’s no telling where the mutation is going to take place.

Then I set two mouseover event handlers on the document; one for the capturing phase and one for the bubbling phase. We can be certain that the first one fires before any author-defined mouseover, and the last one fires after any of them (except when authors actually set mouseovers on the document itself, but that’s rare).

Thus, once a mouseover event occurs the very first thing that happens is that the Mutation Observer is switched on. Once the event has been captured by its target and then bubbled back up to the document we switch off the observer. As a result, only mutations that happen in-between, i.e. on an author-defined mouseover somewhere lower in the DOM tree, are recorded.

I’m happy to report that this works in all browsers. Still, if you think you only get true node changes you should think again.

True node changes and secret text changes

Before we continue, a quick explanation. Mutation Observers can observe three types of mutations:

  1. childList, where a DOM node is added to or removed from the document.
  2. attributes, where a DOM attribute is added, removed, or changed.
  3. characterData, where DOM nodes aren’t touched; only text content is changed.

For this particular job we decided to restrict ourselves to childList mutations: we’re only interested in new DOM nodes that appear in the document.

That sounds good, but it turns out there’s a tricky bit. Take this simple line of code:

element.innerHTML = 'A new text';

Mutation-wise, what’s going on here? Although it seems to be a straight characterData mutation, it’s not.

Let’s say initially element contains a bit of text. In the DOM, this is a text node. What innerHTML does, apparently, is remove this text node entirely and replace it with a new text node that contains the specified text. That makes sense when you think about it for a minute, but it does mean that according to the Mutation Observer this is a childList mutation: nodes are being added and removed.

Also, if element previously contained a <span> or other node, it’s now removed, and that constitutes a true childList mutation.

And what about innerText, textContent, and nodeValue? What kind of mutation do the following lines of code cause?

element.innerText = 'A new text'; element.textContent = 'A new text'; element.firstChild.nodeValue = 'A new text';

The first two are similar to innerHTML. Here, too, text nodes are removed and inserted. The last one is different: here we access a property of the element’s first child node, which is the text node. Here the text node is not removed, but only changed. Thus, browsers see the nodeValue change as a true characterData mutation.

There’s an odd exception here, though. In Chrome, and only Chrome, an innerText change is counted as characterData, provided there were no actual element nodes in element before the code ran. Firefox, Safari, and Edge treat it as a childList mutation in all cases. Why the difference? Is it a bug? I have no clue, but it is something you should be aware of.

In any case, in my script I didn’t want these not-quite-childList mutations cluttering up my records. Fortunately the solution is simple: check if any of the added or removed nodes are element nodes (nodeType === 1). If so this is a true childList mutation; if not it’s a secret characterData mutation.

if (rec.type === 'childList') { var isNodeChange = false; if (rec.addedNodes.length) { for (var i=0,node;node=rec.addedNodes[i];i+=1) { if (node.nodeType === 1) { isNodeChange = true; break; } } } if (rec.removedNodes.length && !isNodeChange) { for (var i=0,node;node=rec.removedNodes[i];i+=1) { if (node.nodeType === 1) { isNodeChange = true; break; } } } if (!isNodeChange) { continue; // continue looping through the records, and ignore this one } } Edge bugs

Unfortunately here we find the first Edge bug. In Edge, innerHTML, innerText, and textContent changes cause not one but two mutation records: one for the removal of the old node, and one for the insertion of the new node. All other browsers have only one mutation record that contains one removed and one inserted node.

That messes up the script above. If, for instance, an element node was removed but not inserted, the insertion record would be seen as characterData, while it should be counted as childList, since the mutation does involve element nodes.

Since Microsoft confirmed this is a bug, and since Edge is not the first, or even second, target browser, we decided to ignore this bug and hope for a speedy fix.

There’s another Edge bug you should be aware of. This is the full configuration object you can send to a mutation observer:

var mutationConfig = { childList: true, subtree: true, characterData: true, attributes: true, attributeOldValue: true, characterDataOldValue: true, };

You’re supposed to only observe those mutation types that you’re interested in in order to avoid a performance hit. I did that in the script above: I only observe childList mutations, though I’m forced to leave subtree on: without it, only mutations on direct children of the HTML element would be counted, and I don’t know where mutations are going to take place. So I observe the entire DOM tree.

The Edge bug concerns the last two entries:

var mutationConfig = { attributeOldValue: true, characterDataOldValue: true, };

These tell the browsers to keep the old values of attributes or text nodes available for use. (If you don’t set these flags they’re discarded.) Since we’re telling browsers to keep track of the old text and attribute values, it stands to reason that we want them to observe those mutations, and Firefox, Safari, and Chrome do so.

Edge doesn’t. It needs explicit orders, like so:

var mutationConfig = { characterData: true, attributes: true, attributeOldValue: true, characterDataOldValue: true, };

Without the first two lines, Edge does nothing. (Actually, it’s more complicated. In my first test Edge gave a JavaScript error without any error text, but in my second it did nothing. I think I moved from 15 to 16 in the mean time, but I’m not 100% sure. Thou shalt always keep a lab journal!)

Anyway, despite the Chrome oddity and the two Edge bugs, Mutation Observers appear ready for prime time.

HTML Email and Accessibility

Css Tricks - Wed, 11/22/2017 - 4:40am

You love HTML emails, don't you?

As a developer, probably not... but subscribers absolutely do. They devour them, consume them on every device known to man, and drive a hell of a lot of revenue for companies that take their email marketing seriously.

But most web developers tasked with building HTML emails merely want to get them out the door as quickly as possible and move on to more interesting assignments. Despite email's perennial value for subscribers, tight timelines, and a general loathing of the work result in things falling by the wayside; and, just like in the web world, one of the first things to be set aside in email is accessibility.

I think we all agree that accessibility is a vital topic. Unfortunately, it's one that's ignored in the email marketing world even more than on the web.

Accessibility in email doesn't have to consume a lot of time, though. There are a few simple practices you can build into your own campaigns that will make your emails more accessible and your subscribers even happier.

Accessible Tables?

One of the main reasons that web developers hate building emails is that we're still stuck using tables for layout in email. Although there are a few different ways to get around using HTML tables, most emails still rely on them to ensure that emails look good in Microsoft Outlook, which doesn't support more traditional CSS positioning, let alone newer CSS layout techniques like Grid (although that's possible in email, too).

But HTML tables present a hurdle for users relying on screen readers for consuming their emails. This is made clear when you hear the output of a screen reader working through the typical HTML email campaign. Mark Robbins of Rebel posted an excellent example of this behavior a while back.

The screen reader is doing it's job: it sees a table, assumes that it contains tabular data, and reads it appropriately.

However, since we're using tables purely for structural purposes, we need screen readers to ignore those tables. This is where ARIA roles can help us out. By applying the role="presentation" attribute to a table, we can instruct the screen reader to skip over those elements and move straight into the content.

See the Pen Accessible Emails - Tables ARIA Presentation by Jason Rodriguez (@rodriguezcommaj) on CodePen.

With that one simple addition, our emails are much more accessible. It should be noted that nested tables don't inherit this behavior, so you will have to apply role="presentation" individually to every table in your campaign. Creating a snippet or building this into your email boilerplate is a good way to ensure accessibility without having to even think about it.

Out of the Image and Into the Code

A common practice in email marketing is to use images for everything in the email: graphics, illustrations, copy, links, and buttons. Although this can be efficient (slice, dice, and send it on its way), it's another huge problem for subscribers relying on screen readers. The typical image-based email has a lot of information that can't be parsed by a machine. What's more is that a lot of email clients disable images by default, too. Ever see something like this?

An example of image-blocking behavior in Microsoft Outlook.

We want to avoid or improve situations where content can't be seen by users or content can't be read by a screen reader. There are two ways to do this.

The first is to rely less on images and more on HTML to convey your message. Pull copy out of your images and put it into your email as real, live text.

HTML text vs. image-blocking. Lyft does this really well.

HTML text isn't susceptible to image blocking in email clients, so it will always be shown. Further, most copy that's typically found within an email can be converted to HTML text. You can style that text however you want, even using web fonts, and your content can be seen by users and understood by screen readers.

This is especially important when it comes to links and buttons in emails. A lot of designers will rely on images for buttons since they can style those buttons however they want. However, those image-based buttons are victims of the same image-blocking behavior as any other image. Using HTML, CSS, and, in some cases, Microsoft's proprietary VML language, you can create code-based buttons that display everywhere and still fit in with your design.

See the Pen Accessible Emails - Bulletproof Buttons by Jason Rodriguez (@rodriguezcommaj) on CodePen.

The second is to rely on alternative text for images. By adding the alt attribute, we can describe the content of images for screen readers so that users get some context and a better understanding of the email.

The same rules apply in email as on the web:

  1. All images should have an alt attribute
  2. Alternative text should present the content and function of an image
  3. Alternative text should never be redundant
  4. Alternative text relies heavily on the context provided by the content surrounding an image
  5. Decorative images should use an empty alt attribute

A simple example of alternative text in an email would be for something like a retail sale.

See the Pen Accessible Emails - Styled ALT Text by Jason Rodriguez (@rodriguezcommaj) on CodePen.

On top of making our emails more accessible, we can actually style that alternative text so that it better fits in with the rest of our email design when images are disabled. Using things like color, font-family, font-size, font-weight, and line-height allows you to style alternative text in largely the same way you would any other text in the email. Combined with something like background-color on the image, these styles make it possible to have highly-optimized—and accessible—emails for when images are disabled.

Styled alternative text keeps emails accessible and on-brand. It's All Semantics

Despite what some email marketers and developers will tell you, semantics in email do matter. Not only do they provide accessible hooks for navigating an email, they can provide fallback styles that help maintain the hierarchy of emails in the unfortunate event CSS isn't loaded or supported.

It used to be that all text styling was done on table cells within a campaign, with any copy being a direct descendant of that table cell.

See the Pen Accessible Emails - Old Text Approach by Jason Rodriguez (@rodriguezcommaj) on CodePen.

Email developers would avoid using semantic elements like headings and paragraphs because email clients (correctly) displayed their own default styling of those elements, which sometimes resulted in broken layouts or unintended designs. I don't know if it was sheer laziness or something else, but very few developers would use semantic elements with simple overrides to keep their designs accessible and consistent across clients.

Adding the margin property on block-level semantic elements—and relying on style inheritance from the table cell—can create more accessible emails that display properly nearly everywhere.

See the Pen Accessible Emails - Semantic Text Approach by Jason Rodriguez (@rodriguezcommaj) on CodePen.

You don't have to stop at simple headings or paragraphs, either. You can use sectioning elements like main, header, footer, article and more to provide extra semantic value to your emails. I would caution you to use them on top of your existing table-based structure, though. Not all email clients support styles being applied to those elements, so something like this is a good approach:

See the Pen Accessible Emails - Semantic Article by Jason Rodriguez (@rodriguezcommaj) on CodePen.

Designing for Subscribers

The last technique I want to discuss—although not the last technique available to us—is adhering to tried-and-true design principles within our campaigns to keep them accessible.

Accessibility isn't all about screen readers. Subscribers can have visual impairments as well as physical or cognitive disabilities that make consuming emails difficult, especially when an email's design hasn't been updated in years. By relying on design principles like hierarchy, space, pattern, proximity, type size, and contrast, we can ensure that a broad spectrum of subscribers can understand and enjoy our email campaigns.

This is especially apparent when it comes to viewing emails on mobile devices. If you're not taking the mobile view into account from the outset, or using responsive email design, then your desktop-first email campaigns can be a pain to use when scaled down on most mobile email clients.

Trello uses large visuals, type, and buttons to keep things readable and usable across all device sizes.

Simply revisiting your designs with mobile and disabled users in mind can go a long way to keeping your emails accessible. Using larger type that's legible for a wide variety of users, combined with proper heading styles and a hierarchy that is easy to scan is a great baseline. Adding in repeatable patterns within your emails that further aid scanning and understanding, along with plenty of white space and properly contrasting colors take your emails even further.

I encourage you to use tools like Chrome Lighthouse and Accessible-Colors.com to check the accessibility of your HTML email designs. It's all HTML and CSS, so the same tools that work on the web work on email as well. Use them!

Have Your Own Tips?

Although a lot of email development is stuck in the past, that doesn't mean we can't modernize our campaigns right along with our websites. Many of these tips can be baked right into your email boilerplate or code snippets, allowing you to create more accessible HTML emails without too much thought.

At the same time, don't let that stop you from putting that extra thought into your emails. This article merely scrapes the surface of what's possible in HTML email development. I'd love to hear about your tips for building accessible emails in the comments below.

HTML Email and Accessibility is a post from CSS-Tricks

Sliders in Web Design: To Use or Not to Use?

Usability Geek - Tue, 11/21/2017 - 2:16pm
Many designers have strong opinions about the use of sliders and slider controls in website design. Some love them; others hate them. A poorly-timed carousel or automated gallery slider can distract...
Categories: Web Standards

Declining Complexity in CSS

Css Tricks - Tue, 11/21/2017 - 2:00pm

The fourth edition of Eric Meyer and Estelle Weyl's CSS: The Definitive Guide was recently released. The new book weighs in at 1,016 pages, which is up drastically from 447 in the third edition, which was up slightly from 436 in the second edition.

Despite the appearance of CSS needing more pages to capture more complicated concepts, Eric suggests that CSS is actually easier to grasp than ever before and its complexity has actually declined between editions:

But the core principles and mechanisms are no more complicated than they were a decade or even two decades ago. If anything, they’re easier to grasp now, because we don’t have to clutter our minds with float behaviors or inline layout just to try to lay out a page. Flexbox and Grid (chapters 12 and 13, by the way) make layout so much simpler than ever before, while simultaneously providing far more capability than ever before.

In short, yes, lots of new concepts have been introduced since 2007 when the third edition was released, but they're solving the need to use layout, err, tricks to make properties bend in ways they were never intended:

It’s still an apparent upward trend, but think about all the new features that have come out since the 3rd Edition, or are coming out right now: gradients, multiple backgrounds, sticky positioning, flexbox, Grid, blending, filters, transforms, animation, and media queries, among others. A lot of really substantial capabilities. They don’t make CSS more convoluted, but instead extend it into new territories.

Hear, hear! Onward and upward, no matter how many pages it takes.

Direct Link to ArticlePermalink

Declining Complexity in CSS is a post from CSS-Tricks

Styleable

Css Tricks - Tue, 11/21/2017 - 7:43am

The Wix dev team throws their hat into the CSS preprocessor ring:

Stylable is a CSS preprocessor that enables you to write reusable, highly-performant, styled components. Each component exposes a style API that maps its internal parts so you can reuse components across teams without sacrificing stylability.

  • Scopes styles to components so they don’t “leak” and clash with other styles.
  • Enables custom pseudo-classes and pseudo-elements that abstract the internal structure of a component. These can then be styled externally.
  • Uses themes so you can apply different look and feel across your web application.

At build time, the preprocessor converts the Stylable CSS into flat, static, valid, vanilla CSS that works cross-browser.

Looks like Sass luminary Chris Eppstein is getting in on the game of scoped styles with the not-yet-released CSS Blocks. And think of Vue's support for <style scoped>, and the popularity of utility libraries. I think scoped styles might be the hottest CSS topic in 2018.

Direct Link to ArticlePermalink

Styleable is a post from CSS-Tricks

Advocating for Accessible UI Design

Css Tricks - Tue, 11/21/2017 - 4:05am

Accessibility is a hot topic these days, and the older we web-makers get, the hotter it's going to become! That might be a snarky outlook, but what I'm trying to say is that it's about time we start designing the web for everyone because the web was meant to be for everyone, and less and less are we able to predict where, when, and how our work will be consumed.

Accessibility is not just up to developers

As developers, we often encounter accessibility post-design, when we do things like implementating the correct role and aria attributes, ensuring navigation is keyboard friendly, and responsibly hiding elements. In general, our accessibility efforts go towards thinking about how to make specific components and features accessible, such as an SVG icon system or helpful tool-tips.

Given our roles as developers, this makes sense. Accessibility flaws, however, often originate in the UI design itself, and depending on our work environment, we developers don't necessarily have the authority or bandwidth to advocate for accessibility in the designs we are handed.

For example, let's say you are tasked with turning a Sketch file into a one-page WordPress site.

The design has finally been approved by the client, and now you have a weekend to build the thing, plus another two days to work with QA to perfect it. As you take a look at the design for the first time, you notice that, on small devices, the dainty serif typeface overlaid on a background image would be difficult for low-sighted visitors to read.

You, the accessibility-minded developer, could proceed in a few ways:

  1. Remain silent and sate your accessibility conscience by making accessible choices in the code where you can
  2. Go ahead and make accessibility improvements to the UI as you develop, present them in the finished product, and explain yourself after
  3. Compile a list of suggested changes to send to the designer and request they be implemented in the mockups so you can then develop them

I was in a situation like this recently and, judge me if you will, I chose number one.

If I'd had the time and the guts, number 2 would've gotten me the furthest, but given the nature of my role as a first-time contractor at this high-speed agency I was hoping to develop a working relationship with, I felt I'd be overstepping my bounds and wasn't ready to take the risk of being too vocal out of the gate. I chose not to do number 3 for similar reasons, mainly for fear of causing more work and stress for the already extremely busy designer.

Now that I have the benefit of hindsight, however, might I add a fourth item to the list?

  1. Send a succinct list of non-technical accessibility tips for UI design to everyone on the team so they make more accessible design choices in future

Where to find such a list? Well, you are in luck! Read on!

Non-technical Accessibility Tips for UI Design

What follows is a list of plain language, no-jargon, "Accessibility Tips for UI Design" you, developer, can share with everyone at work: UI designers, content providers, project managers, and clients alike. The more we can spread awareness about accessibility and think critically about the mockups we are handed to implement, the more accessible the web will be!

I have chosen the examples below from various trendy website feeds, and I used the fantastic Funkify Chrome Extension to simulate the viewing experience of site visitors with varying abilities and disabilities.

First up:

Easy on the animations.

With great power comes great responsibility. The modern web affords us the power to bounce-in, fly-in, or drop-in any content we please, but besides the wow factor, how are these animations contributing to a reader's experience on your site? How are the animations triggered? Can they be mistakenly triggered, causing a confusing jolt in the flow of your site visitor's experience?

Take this example of a car repair company's website. I've applied the "Elderly Ellen" filter from Funkify to simulate slightly blurred vision and shaky hands:

Elderly Ellen's trembling hands cause a jarring experience with bold animations.

If I were Ellen, this experience would likely steer me away from Service King's services! Someone like Elderly Ellen is constantly frustrated with technology. It's unnecessary to cause her that stress when she's trying to read about a service for repairing her car after an already traumatizing fender bender.

Make sure background and text colors have enough contrast.

Although that medium grey text looks just right on that light grey background, it's hard to read...and impossible to read if you are working out in the sunshine (not a common occurance, but I've done it before). Here's an example of the aforementioned grey-on-grey scenario:

The medium grey text color of these icons' captions does not contrast enough with the light grey background color.

And now, the same example affected by the "Sunshine Sue" filter from Funkify deems our low contrast captions simply invisible!

And now, simulating sunshine on a screen, the text is completely gone!

The solution? Run your color choices through the WebAIM contrast checker to see if they meet standards for readability and color contrast, and if they don't, adjust the color values until they do.

The Funkify extension can be used to test anything that is visible in a browser. Even if a design mock isn't yet implemented in code, an image or PDF can be opened in the browser and the extension will still work!

Be very careful when overlaying text on images, or don't.

It might look just right to have that dainty serif overlaid on the big header image, but can you read it if you slightly blur your vision? If not, up the contrast between the text and image, perhaps by brightening the text color and increasing the transparency of the image on a dark background.

On Burberry's website, for example, the user must select from a drop-down in order to enter the site, but the text identifying the drop-down is barely readable over top the background image. There are many ways to solve this from a design standpoint, but for a quick example, we could add a dark background beneath the light text to provide a bit more contrast:

Adding a contrasting background beneath the text overlaid on an image can help with readability.

Similarly, while the delicate descriptive text below the image on Tesla's new Semi website is delicate and beautiful, it is barely legiible when simulating slightly blurred vision with "Blurry Bianca":

The descriptive text overlaid on the bottom of this image is barely legible when simulating slightly blurred vision. Double-check the readability of font weights and sizes.

The thinner the font weight and the smaller the size, the harder it is to read. Even I, as a hearing, well-sighted individual, find myself zooming in on body text at times because it is so darn lightweight and small, even if the color contrast is up to speed. If you must stick with the lightweight font, increasing the sizes and line height can do wonders as well.

I like to ask myself, does it pass the slightly-cross-eye test? That is when I slightly cross my eyes, can I still make out the text?

Some contrast, line-height, and font-size adjustments make for a more readable text in a disclaimer we are supposed to read. Indicate external links.

If it is a requirement for a link to open in a new tab, first question whether it should be a requirement, then indicate it visually with a small icon or note in the UI.

Additionally, designers can make a note in their designs where there should be screen-reader-only text indicating the link will navigate the user away from their current viewing portal. This was brought to mind by way of some excellent replies to a Twitter conversation; read through that here.

Differentiate between action-oriented social media links vs. profile links.

When we see small social media icons, I think the general assumption is that they link to the relevant social media profiles. Sometimes, however, these icons are actually actions that, rather than linking to a profile, open a "New Tweet" dialog or similar. These actions should be marked as such.

Don't rely 100% on icons and colors to communicate.

It's easy to assume everyone knows that a hamburger icon indicates a menu or that everyone is familiar with the various versions of LinkedIn's icon. However, this is not the case, and it causes a moment of confusion and insult that isn't necessary to site visitors that are less in-the-know than we are. Especially if your audience tends to be older and/or less tech-savvy, make sure you aren't relying on what you think is common knowledge.

Reliance on colors for meaning causes a similar issue, and more-so for any users that deal with color blindness. A recent Smashing Magazine article covers this problem in detail and uses the example of a color picker on shoe sales website that, for color-blind users, results in an entirely different palette.

What would the design look like without interactivity?

If all a user could do was scroll, does the content still make sense? Are there areas where, rather than hiding the thumbnail caption under a fancy hover event, the caption could be plainly visible instead? What about on a touch screen, where hover events are treated quite differently?

What else?

Have you encountered issues with accessibility in designs you've implemented? How did you handle it? What other tips can we give designers and producers for creating more accessible UI designs?

The first step to advocating for accessible UI design is to simply think twice about what you, the developer, are told to implement. While coding up a design, try applying a few of these Funkify filters and see what results they yield. Think critically about the designs you are handed, and start a conversation with your coworkers.

Advocating for Accessible UI Design is a post from CSS-Tricks

Syndicate content
©2003 - Present Akamai Design & Development.