Level up your .filter game


.filter is a built-in array iteration method that accepts a predicate which is called against each of its values, and returns a subset of all values that return a truthy value.

That is a lot to unpack in one statement! Let’s take a look at that statement piece-by-piece.

  • “Built-in” simply means that it is part of the language—you don’t need to add any libraries to get access to this functionality.
  • “Iteration methods” accept a function that are run against each item of the array. Both .map and .reduce are other examples of iteration methods.
  • A “predicate” is a function that returns a boolean.
  • A “truthy value” is any value that evaluates to true when coerced to a boolean. Almost all values are truthy, with the exceptions of: undefined, null, false, 0, NaN, or "" (empty string).

To see .filter in action, let’s take a look at this array of restaurants.

const restaurants = [
    {
        name: "Dan's Hamburgers",
        price: 'Cheap',
        cuisine: 'Burger',
    },
    {
        name: "Austin's Pizza",
        price: 'Cheap',
        cuisine: 'Pizza',
    },
    {
        name: "Via 313",
        price: 'Moderate',
        cuisine: 'Pizza',
    },
    {
        name: "Bufalina",
        price: 'Expensive',
        cuisine: 'Pizza',
    },
    {
        name: "P. Terry's",
        price: 'Cheap',
        cuisine: 'Burger',
    },
    {
        name: "Hopdoddy",
        price: 'Expensive',
        cuisine: 'Burger',
    },
    {
        name: "Whataburger",
        price: 'Moderate',
        cuisine: 'Burger',
    },
    {
        name: "Chuy's",
        cuisine: 'Tex-Mex',
        price: 'Moderate',
    },
    {
        name: "Taquerias Arandina",
        cuisine: 'Tex-Mex',
        price: 'Cheap',
    },
    {
        name: "El Alma",
        cuisine: 'Tex-Mex',
        price: 'Expensive',
    },
    {
        name: "Maudie's",
        cuisine: 'Tex-Mex',
        price: 'Moderate',
    },
];

That’s a lot of information. I’m currently in the mood for a burger, so let’s filter that array down a bit.

const isBurger = ({cuisine}) => cuisine === 'burger';
const burgerJoints = restaurants.filter(isBurger);

isBurger is the predicate, and burgerJoints is a new array which is a subset of restaurants. It is important to note that restaurants remained unchanged from the .filter.

Here is a simple example of two lists being rendered—one of the original restaurants array, and one of the filtered burgerJoints array.

See the Pen .filter – isBurger by Adam Giese (@AdamGiese) on CodePen.

Negating Predicates

For every predicate there is an equal and opposite negated predicate.

A predicate is a function that returns a boolean. Since there are only two possible boolean values, that means it is easy to “flip” the value of a predicate.

A few hours have passed since I’ve eaten my burger, and now I’m hungry again. This time, I want to filter out burgers to try something new. One option is to write a new isNotBurger predicate from scratch.

const isBurger = ({cuisine}) => cuisine === 'burger';
const isNotBurger = ({cuisine}) => cuisine !== 'burger';

However, look at the amount of similarities between the two predicates. This is not very DRY code. Another option is to call the isBurger predicate and flip the result.

const isBurger = ({cuisine}) => cuisine === 'burger';
const isNotBurger = ({cuisine}) => !isBurger(cuisine);

This is better! If the definition of a burger changes, you will only need to change the logic in one place. However, what if we have a number of predicates that we’d like to negate? Since this is something that we’d likely want to do often, it may be a good idea to write a negate function.

const negate = predicate => function() {
  return !predicate.apply(null, arguments);
}

const isBurger = ({cuisine}) => cuisine === 'burger';
const isNotBurger = negate(isBurger);

const isPizza = ({cuisine}) => cuisine === 'pizza';
const isNotPizza = negate(isPizza);

You may have some questions.

What is .apply?

MDN:

apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

What is arguments?

MDN:

The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function’s arguments within the function by using the arguments object.

Why return an old-school function instead of a newer, cooler arrow function?

In this case, returning a traditional function is necessary because the arguments object is only available on traditional functions.

Returning Predicates

As we saw with our negate function, it is easy for a function to return a new function in JavaScript. This can be useful for writing “predicate creators.” For example, let’s look back at our isBurger and isPizza predicates.

const isBurger = ({cuisine}) => cuisine === 'burger';
const isPizza  = ({cuisine}) => cuisine === 'pizza';

These two predicates share the same logic; they only differ in comparisons. So, we can wrap the shared logic in an isCuisine function.

const isCuisine = comparison => ({cuisine}) => cuisine === comparison;
const isBurger  = isCuisine('burger');
const isPizza   = isCuisine('pizza');

This is great! Now, what if we want to start checking the price?

const isPrice = comparison => ({price}) => price === comparison;
const isCheap = isPrice('cheap');
const isExpensive = isPrice('expensive');

Now the isCheap and isExpensive are DRY, and isPizza and isBurger are DRY—but isPrice and isCuisine share their logic! Luckily, there are no rules for how many functions deep you can return.

const isKeyEqualToValue = key => value => object => object[key] === value;

// these can be rewritten
const isCuisine = isKeyEqualToValue('cuisine');
const isPrice = isKeyEqualToValue('price');

// these don't need to change
const isBurger = isCuisine('burger');
const isPizza = isCuisine('pizza');
const isCheap = isPrice('cheap');
const isExpensive = isPrice('expensive');

This, to me, is the beauty of arrow functions. In a single line, you can elegantly create a third-order function. isKeyEqualToValue is a function that returns the function isPrice which returns the function isCheap.

See how easy it is to create multiple filtered lists from the original restaurants array?

See the Pen .filter – returning predicates by Adam Giese (@AdamGiese) on CodePen.

Composing Predicates

We can now filter our array by burgers or by a cheap price… but what if you want cheap burgers? One option is to simply chain to filters together.

const cheapBurgers = restaurants.filter(isCheap).filter(isBurger);

Another option is to “compose” the two predicates into a single one.

const isCheapBurger = restaurant => isCheap(restaurant) && isBurger(restaurant);
const isCheapPizza = restaurant => isCheap(restaurant) && isPizza(restaurant);

Look at all of that repeated code. We can definitely wrap this into a new function!

const both = (predicate1, predicate2) => value =>
  predicate1(value) && predicate2(value);

const isCheapBurger = both(isCheap, isBurger);
const isCheapPizza = both(isCheap, isPizza);

const cheapBurgers = restaurants.filter(isCheapBurger);
const cheapPizza = restaurants.filter(isCheapPizza);

What if you are fine with either pizza or burgers?

const either = (predicate1, predicate2) => value =>
  predicate1(value) || predicate2(value);

const isDelicious = either(isBurger, isPizza);
const deliciousFood = restaurants.filter(isDelicious);

This is a step in the right direction, but what if you have more than two foods you’d like to include? This isn’t a very scalable approach. There are two built-in array methods that come in handy here. .every and .some are both predicate methods that also accept predicates. .every checks if each member of an array passes a predicate, while .some checks to see if any member of an array passes a predicate.

const isDelicious = restaurant =>
  [isPizza, isBurger, isBbq].some(predicate => predicate(restaurant));

const isCheapAndDelicious = restaurant =>
  [isDelicious, isCheap].every(predicate => predicate(restaurant));

And, as always, let’s wrap them up into some useful abstraction.

const isEvery = predicates => value =>
  predicates.every(predicate => predicate(value));

const isAny = predicates => value =>
  predicates.some(predicate => predicate(value));

const isDelicious = isAny([isBurger, isPizza, isBbq]);
const isCheapAndDelicious = isEvery([isCheap, isDelicious]);

isEvery and isAny both accept an array of predicates and return a single predicate.

Since all of these predicates are easily created by higher order functions, it isn’t too difficult to create and apply these predicates based on a user’s interaction. Taking all of the lessons we have learned, here is an example of an app that searches restaurants by applying filters based on button clicks.

See the Pen .filter – dynamic filters by Adam Giese (@AdamGiese) on CodePen.

Wrapping up

Filters are an essential part of JavaScript development. Whether you’re sorting out bad data from an API response or responding to user interactions, there are countless times when you would want a subset of an array’s values. I hope this overview helped with ways that you can manipulate predicates to write more readable and maintainable code.

The post Level up your .filter game appeared first on CSS-Tricks.



Source link

Unity Finalizes Move to WebAssembly with the Unity 2018.2 Release


Unity Technologies, a real-time 3D (RT3D) development platform provider, has completed its move to WebAssembly with the Unity 2018.2 release. In June 2017, ProgrammableWeb reported that WebAssembly had reached cross-browser consensus status, and that all the major browser companies are currently working on designing wasm as an open standard.





Source link

Firefox Multi-Account Containers


It’s an extension:

Each Container stores cookies separately, so you can log into the same site with different accounts and online trackers can’t easily connect the browsing.

A great idea for a feature if you ask me. For example, I have two Buffer accounts and my solution is to use different browsers entirely to stay logged into both of them. I know plenty of folks that prefer the browser version of apps like Notion, Front, and Twitter, and it’s cool to have a way to log into the same site with multiple accounts if you need to — and without weird trickery.

This is browsers competing on UI/UX features rather than web platform features, which is a good thing. Relevant: Opera Neon and Refresh.

Direct Link to ArticlePermalink

The post Firefox Multi-Account Containers appeared first on CSS-Tricks.





Source link

Seriously, though. What is a progressive web app?


Amberley Romo read a ton about PWAs in order to form her own solid understanding.

“Progressive web app” (PWA) is both a general term for a new philosophy toward building websites and a specific term with an established set of three explicit, testable, baseline requirements.

As a general term, the PWA approach is characterized by striving to satisfy the following set of attributes:

  1. Responsive
  2. Connectivity independent
  3. App-like-interactions
  4. Fresh
  5. Safe
  6. Discoverable
  7. Re-engageable
  8. Installable
  9. Linkable

Direct Link to ArticlePermalink

The post Seriously, though. What is a progressive web app? appeared first on CSS-Tricks.



Source link

Designing For Micro-Moments


Designing For Micro-Moments

Designing For Micro-Moments

Suzanna Scacca

2018-08-17T13:50:09+02:00
2018-08-17T12:41:01+00:00

A couple of years ago, Google announced a new mobile-first initiative it wanted web designers and marketers to pick up on. This was our introduction to micro-moments.

These are not to be confused with micro-interactions, which are miniscule engagements websites have with visitors when they “touch” key points of the interface. A mouse changes its appearance when a user hovers over a clickable element. A display error appears after a field is incorrectly populated. A checkbox briefly enlarges and changes color after it’s been ticked off. These are micro-interactions.

A micro-moment, however, originates with your visitor. In Myriam Jessier’s “Things Designers Should Know About SEO In 2018“, she sums up Google’s four micro-moments:

  1. “I want to know.”
  2. “I want to go.”
  3. “I want to do.”
  4. “I want to buy.”

Basically, these are four key moments in every consumer’s life when they decide to pick up their mobile device for a specific purpose. As such, it’s your job to know how to specifically design for these micro-moments.

Recommended reading: What You Need To Know To Increase Mobile Checkout Conversions

How You Should Be Designing For Micro-Moments

When a visitor arrives at a mobile website (or app), they’ve come with a clear motivation:

  1. “I want to know.”
  2. “I want to go.”
  3. “I want to do.”
  4. “I want to buy.”

Seems pretty simple, right? However, as Google launched this initiative a couple of years ago, its had time to quietly observe users in these micro-moments as well as the websites that have most aptly responded to them. As you will soon see, consumers have incredibly high expectations for what the mobile web can do for them. Basically, they want you to be a mind reader and anticipate their every need (and even their location) without them having to say a word.

Is that intimidating? It shouldn’t be. You already have all the information you’d ever need to answer that question.

Here is how you should be designing your mobile website to respond to and draw in consumers as they experience these micro-moments:

1. Start With The Data

Google Analytics will help you decipher where they’re spending the most time productively on your website.


Google Analytics Behavior breakdowns
An example of Google Analytics’ visitor behavior breakdowns. (Source: Google Analytics) (Large preview)

Google Search Console will tell you which keywords are most effective in driving high-quality leads to the site.


Google Search Console keywords
An example listing of keywords and associated clicks and impressions for a website. (Source: Google Search Console) (Large preview)

Once you know where exactly visitors see the greatest value in your product, you can then turn to third-party tools like Answer the Public to give you some insights into what relevant questions your users may be asking about you.


Answer the Public sample answers
An example of how Answer the Public provides micro-moment answers. (Source: Answer the Public) (Large preview)

Ultimately, this data needs to tell you all about your customers’ journey before they ever reach you. What exactly was the question that triggered them to pick up their smartphone and do that search? If you can identify those micro-moments, you can start using various design elements to respond to these questions.

2. Respond With Immediacy

According to Google:

People are searching at the exact moment they need something and are looking for places that can meet their immediate need. In other words, when making these on-the-spot decisions, they are more loyal to their need than to any particular place.

Although we’ve heard a lot about customer loyalty to brands in the past, it’s interesting to get Google’s take on this matter.

While consumers may indeed still remain loyal to brands that take very good care of them and produce a high-quality product nearly 100% of the time, this opportunity to steal attention from those customers in one of their micro-moments is real. Do that enough times and your brand and website could realistically win that customer over so long as you are there every time they go searching to fill that need.

One of the ways you can do this is by providing users with instant solutions. Is your business open now? Can you mail out that new product same-day? Will there be an open table at your restaurant tonight? Answer that immediately and you could find conversions increase dramatically.

Take the Delaware State Fair website, for example.


Delaware State Fair gives users what they need to know
The top of the Delaware State Fair home page gives users easy access to everything they want to know and do. (Source: Delaware State Fair) (Large preview)

Look at the top of the homepage. There are the dates of the fair, which probably answer one of the most commonly searched questions. There is a link to the concert lineup as well as calendar, which answers anything people would want to know about special events they might want to go to. And then there’s a button to buy tickets right away. It’s all right there.

Office Depot is a company that also explicitly addresses immediate needs:


Office Depot includes time-driven design elements
The Office Depot mobile site uses a variety of time-driven design elements to satisfy visitors’ needs. (Source: Office Depot) (Large preview)

As you can see in the example above, Office Depot uses a number of design tactics and elements to play into this need for immediacy.

  • There is a search bar at the very top. Consumers don’t have to even bother with navigation or scrolling through pages if they don’t want to/have the time to.
  • You’ll also see that the closest store’s hours are posted and boldly tell me how quickly I can have any products available in store.
  • Finally, you have the promotional categories for upcoming needs for parents that are about to send kids back to school.

Another website is Universal Studios Orlando; it does a great job sparing mobile users the trouble of sifting through irrelevant information and instead gets them to exactly what they need:


Universal Studios provides immediate research and booking options
Universal Studios includes immediate options for research and booking on the home page and navigation. (Source: Universal Studios) (Large preview)

Aside from a single banner at the top of the home page, the Universal Studios website design gives visitors exactly what they want right away. The navigation includes only the most pertinent links to information and booking as does this succinct section on the home page. There’s really no time to waste when the options are so clear.

And here is one final example of a website that deals in immediacy, albeit with a more subtle design technique: Nordstrom:


Nordstrom uses color for immediacy
Nordstrom appeals to immediacy with this one subtle trick. (Source: Nordstrom) (Large preview)

As you can see, this is a pretty typical e-commerce product page. However, there’s one key difference: Nordstrom is subtly calling attention to its Anniversary Sale and the main reason why there is a significant price drop for this purchase. Rather than use an obtrusive pop-up to announce the sale and pester users to shop, it’s made the price change directly on the page and drawn attention to it with the highlighted text.

3. Respond With Relevant Content

According to Google:

Not only have mobile searches for ‘best’ grown over 80% in the past two years, but searches for ‘best’ have shown higher growth among ‘low-consideration’ products than ‘high-consideration’ products. In other words, we’re all becoming research-obsessed, even about the small stuff.

We understand that the opinions of family, friends, and colleagues matter greatly in the minds of consumers. But as more and more of them to turn the web to make their purchases, it means being open to trusting other opinions online as well — ones that may be more conveniently expressed from a company’s website, from an influencer’s blog, or from social media.

Wherever those words of wisdom happen to come from, it’s important to take Google’s research to heart. With so many consumers now obsessed with this idea of having the best of everything and being able to get it in a pinch, your website needs to be the answer to that question.

But that’s the tricky part. According to Google, it’s not as simple as being a dog food manufacturer and configuring your site to be the answer to:

“Best Dog Food”

Consumers experience these micro-moments at a granular level. Sure, there may be some who think, “What is the best dog food?” But isn’t it more likely that question would be more specific in nature? For instance:

  • Best puppy food?
  • Best grain-free dog food?
  • Best vegan dog food?

Let’s take a look at Google, for example. Here’s a variety of searches for a singular “best of” concept:


Best searches example from Google
Example of the variety in “Best” searches in Google. (Source: Google) (Large preview)

As you can see, it goes beyond the basic questions. Through your design and your content, you must be ready to answer the most relevant questions your users have about your product or service.

With content, you’ll be able to answer many of the “I want to know” questions that are related to the brand with things like:

  • Informational pages regarding services and products.
  • Whitepapers, ebooks, case studies, reports, and other long-form content that provide heavily researched answers on related matters.
  • Blog posts, vlogs, podcasts, and other shorter content that can dabble more in appealing to the emotions of consumers.
  • Tutorials and guides that directly answer questions that consumers are asking.

As far as the design piece is concerned, it’s your responsibility to highlight these pages, so visitors don’t have to dig through various parts or layers of the site (like the footer or secondary navigation) to find their answers.

Google told them it was here, so it’s your job to get them right to it.

The navigation will play a big part in this, as evidenced by Globus Journeys:


Globus answers users in the navigation
Globus Journeys provides answers to micro-moments in the navigation. (Source: Globus Journeys) (Large preview)

As you can see in this example, Globus Journeys answers many of those micro-moments right within the navigation: tips on touring (Touring 101), tips on travel best practices (Travel Tips), deals available for travel (Deals & Offers), etc.

Another way to use navigational design to inform visitors on what they’ll learn/know from this experience can take place on the blog. Salesforce has an interesting example of this:


Salesforce has informative blog navigation
Salesforce includes a navigation menu for the blog. (Source: Salesforce) (Large preview)

There is the standard navigation for the Salesforce website, and then there is the navigation that’s specific to the Salesforce blog. This gives you — as the designer and planner of the site’s layout — a chance to better and more clearly organize content found within it. So, when visitors show up and want to know tips specific to one of those categories, it doesn’t require random searches or (even worse) endless scrolling through a full blog feed.

Another way you can more quickly and thoroughly inform visitors on topics of interest to them is by using strategically placed sections within blog posts.

While you likely won’t have anything to do with the writing of a website’s blog content, you will have control over its layout and formatting. The first thing you can do to expedite the knowledge acquisition process is by using callouts to detail and link to the various sections covered on the page as Be Brain Fit does:


Be Brain Fit has an index of topics
Be Brain Fit calls out a linkable index of topics from the blog post. (Source: Be Brain Fit) (Large preview)

Of course, the post itself is easy to scan, so readers could guide themselves to the most relevant parts. However, by placing this towards the top of the piece, you’re enabling them to get right to the information they seek.

I’m also going to suggest that pop-ups would be helpful in this matter.

I know, I know. Mobile pop-ups can be annoying, but not when they’re used properly as Fit Small Business has done here.


Fit Small Business uses a helpful pop-up
Fit Small Business not only provides all the information needed, but also offers an alternative solution to what they seek. (Source: Fit Small Business) (Large preview)

I encountered this blog post after doing a search for the best way to create a Facebook page. This was one of the links on the first SERP. I was actually quite pleased with the post as a whole. It broke it up into easy-to-follow steps, attractive and informative visuals, and got me the answer I needed.

However, I was especially pleased to see the bottom banner pop-up after I finished getting through the post. Not only has Fit Small Business attempted to reach its audience by providing helpful content, but it’s also providing an alternative solution to anyone who got here and realized, “Eh, I really don’t want to bother with this on my own.”

4. Respond With Geotargeting

According to Google:

Looking for something nearby — a coffee shop, noodle restaurant, shoe store — is one of the most common searches we do. In fact, nearly one-third of all mobile searches are related to location.

Here’s the thing though: users aren’t using “near me” qualifiers as much anymore.


Near me qualifiers dropping in use
Google demonstrates how location qualifiers are decreasing in use. (Source: Google) (Large preview)

According to Google, this is because many consumers now assume that search engines, websites, and mobile apps are tracking this sort of information already. They expect that if they search for something like “dog food,” Google will automatically serve them the most relevant results — and that includes taking into account location proximity.

In Google’s research, it found that about two-thirds of mobile consumers are more likely to buy something from a website or app if information is geographically personalized. There are a plethora of ways to communicate this local-friendliness to visitors — through the copy, through various design elements, and even photos.

Google is a pioneer in this space and so I want to give it a special shout-out in this section for what it does with search results:


Google auto-populates search questions.
Google’s auto-populated search results aren’t just for Google. (Source: Google) (Large preview)

The biggest thing to take away from here is the fact that Google provides its users with auto-populated search recommendations. These are based on the users’ geography, behavior, history, as well as what Google knows about the query itself. As you can see here, it expands on Baltimore to provide more specific results based on the area of the city in which the user wants to drink.

With AI-assisted search functionality, any website can offer this same level of smart search for its users.

Of course, you first need to get access to visitors’ geographic data before you can provide them with these kinds of smart and geographically relevant results. One way to do this is to require them to sign in and fill out a profile with these details. Another way, however, is by serving them with this geotargeting request as Best Buy has done:


Best Buy asks for geo access
Best Buy requests for access to users’ geographic location. (Source: Best Buy) (Large preview)

Once you have access to a visitors’ current location, however, you can start providing them with information that helps them with the “I want to go”, “I want to do”, and the “I want to buy” micro-moments that caused them to reach for the phone in the first place.

Here is what the Best Buy website shows me after I granted it permission:


Best Buy provides geo-specific details
Best Buy uses its visitors’ location to provide helpful in-store visit details. (Source: Best Buy) (Large preview)

The top of the page now displays the nearest location to me as well as opening hours. As I peruse the rest of the site, I will receive relevant information regarding in-store product availability, buy-online-pick-up-in-store options, and so on. This is a really great option for businesses with a sales website and brick-and-mortar location that want to merge the two experiences.

You could also benefit from using this on websites that offer services, appointments, and reservations. Here is an example of what The Palm Restaurant does with my information:


The Palm Restaurant geotargeting
The Palm Restaurant streamlines the reservation process with geotargeting. (Source: The Palm Restaurant) (Large preview)

To start, it uses my information to let me know right away if there even is a location close to me. Philadelphia isn’t too far, but it’s still nice to have the address fully displayed so I can make up my mind about whether I want to dine there. And, if I do, I can choose the “Reservations” button above it.

What’s especially nice about this is that the reservation form is pre-populated:


The Palm Restaurant streamlines conversion
The Palm pre-populates its reservation form based on user information. (Source: The Palm Restaurant) (Large preview)

As you can see, it’s used a mixture of my geographic location along with the most popular reservation types (i.e. two people at 7 p.m.) to pre-populate the form. This saves me, as the user, time in filling it out and making my reservation.

5. Respond With Convenience

According to Google:

Every day, people are becoming more reliant on their smartphones to help make last-minute purchases or spur-of-the-moment decisions. In fact, smartphone users are 50% more likely to expect to purchase something immediately while using their smartphone compared to a year ago.

Recently, I wrote a post about what you need to know to increase mobile checkout conversions. The underlying message was that mobile consumers have certain expectations that need to be met if you intend on converting them there (as opposed to switching back to desktop).

  • Convenience in getting the information they want is one of them.
  • Speed in getting to and through checkout is another.
  • Handling their contact and payment information securely is the final piece.

Clearly, web designers are doing something right as over half of smartphone users reach for their phone to buy something and subsequently do. But it can’t stop with the 10 tips offered in that article. You need to be able to predict what they’re going to purchase and what exactly they want to do when you catch them in those exact micro-moments.

Let’s use UPack as one example.


UPack shows a price quote form first thing
UPack includes a price quote form at the very top of the website. (Source: UPack) (Large preview)

At the very top of every page is a short price quote form that asks only the most pertinent details they need in order to provide a quote to interested customers. By anticipating that’s what they’re looking to do when they visit a moving company’s website, UPack likely experiences very high conversion rates.

However, if someone should arrive at this form and wonder, “Should I even bother with a quote from UPack?”, they’ve provided an answer to that on the next step down on the home page:


UPack’s explainer graphic reaches users on the fence
UPack uses an explainer graphic to sell the value of its service right away. (Source: UPack) (Large preview)

This explainer graphic is simple. It includes four points and shows how exactly someone uses the UPack service to move their home from one destination to another. When someone arrives there with the intention of getting help with their move, UPack has already made it all the more simple in just one scroll and two panels of the home page.

Then, you have a company like HostGator that doesn’t waste any time at all:


HostGator provides shortcut to purchase
HostGator’s home page includes smart design callouts that sum up its services. (Source: HostGator) (Large preview)

If someone shows up on a web hosting company’s website — especially one that is well known as they are — of course they know what they want to do. Now, they could hop into the navigation and dig deeper into the various hosting plans (which some may do). However, HostGator is probably hoping to appeal to two specific audiences with these “Buy Now!” callouts on the home page:

  • The web developer who knows exactly which plan he or she needs, and doesn’t need a full page to explain the benefits to him.
  • The small business owner who doesn’t know a thing about web hosting, but trusts HostGator’s good name and just wants to get their web hosting purchases ASAP.

This is a really good choice of design techniques if you know that a good portion of your audience will be immediately ready to buy upon entering the site. If they don’t have to click through to another site, don’t make them do it.

And, of course, CTAs, in general, are an important element to use when designing for micro-moments. When they’re designed well — colorful, large, well-labeled — you’re essentially giving your users a shortcut to conversion.

BarkBox uses a number of these right on its home page:


BarkBox’s CTA shortcuts
BarkBox has a number of CTA shortcuts available on its website. (Source: BarkBox) (Large preview)

Since the brand is particularly well-known among dog owners, this is a good move. While there are some people who enjoy scrolling through the site to see the funny dog pictures and find out more about what’s in this month’s BarkBox, if they’ve arrived here on mobile, they shouldn’t have to wait to subscribe. BarkBox provides those shortcuts in a number of locations, ensuring there’s no friction between its customers and their goals.

Wrapping Up

It’s pretty amazing to watch the web change so quickly as consumers become more trusting of their mobile devices. Now, nearly two years after Google first began recommending that we design with micro-moments in mind, it appears that these suggestions have really paid off.

Designing for micro-moments gives us the opportunity to more effectively reach consumers in their moment of need. This, consequently, means reaching consumers who are in a more purchase-intent mindset as opposed to ones casually browsing the web. If you can use your data and design to actively reach consumers in their micro-moments, you can effectively increase your mobile site’s conversion rate in the years to come.

Smashing Editorial
(lf, ra, yk, il)



Source link

Easy and Responsive Modern CSS Grid Layout


In this article, I’ll show how to create a responsive modern CSS Grid layout, demonstrating how to use fallback code for old browsers, how to add CSS Grid progressively, and how to restructure the layout in small devices and center elements using the alignment properties.

In a previous article we explored four different techniques for easily building responsive grid layouts. That article was written back in 2014 — before CSS Grid was available — so in this tutorial, we’ll be using a similar HTML structure but with modern CSS Grid layout.

Throughout this tutorial, we’ll create a demo with a basic layout using floats and then enhance it with CSS Grid. We’ll demonstrate many useful utilities such as centering elements, spanning items, and easily changing the layout on small devices by redefining grid areas and using media queries. You can find the code in this pen:

See the Pen css-grid-example4 by SitePoint (@SitePoint) on CodePen.

Before we dive into creating our responsive grid demo, let’s first introduce CSS Grid.

CSS Grid is a powerful 2-dimensional system that was added to most modern browsers in 2017. It has dramatically changed the way we’re creating HTML layouts. Grid Layout allows us to create grid structures in CSS and not HTML.

CSS Grid is supported in most modern browsers except for IE11, which supports an older version of the standard that could give a few issues. You can use caniuse.com to check for support.

A Grid Layout has a parent container with the display property set to grid or inline-grid. The child elements of the container are grid items which are implicitly positioned thanks to a powerful Grid algorithm. You can also apply different classes to control the placement, dimensions, position and other aspects of the items.

Let’s start with a basic HTML page. Create an HTML file and add the following content:

<header>
    <h2>CSS Grid Layout Example</h2>
</header>
<aside>
  .sidebar
</aside>

<main>
  <article>
    <span>1</span>
  </article>
  <article>
    <span>2</span>
  </article>
  <!--... -->
  <article>
    <span>11</span>
  </article>
</main>

<footer>
  Copyright 2018
</footer>

We use HTML semantics to define the header, sidebar, main and footer sections of our page. In the main section, we add a set of items using the <article> tag. <article> is an HTML5 semantic tag that could be used for wrapping independent and self-contained content. A single page could have any number of <article> tags.

This is a screen shot of the page at this stage:

The basic HTML layout so far

Next, let’s add basic CSS styling. Add a <style> tag in the head of the document and add the following styles:

body {
  background: #12458c;
  margin: 0rem;
  padding: 0px;
  font-family: -apple-system, BlinkMacSystemFont,
            "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
            "Fira Sans", "Droid Sans", "Helvetica Neue",
            sans-serif;
}

header {
  text-transform: uppercase;
  padding-top: 1px;
  padding-bottom: 1px;
  color: #fff;
  border-style: solid;
  border-width: 2px;
}

aside {
  color: #fff;
  border-width:2px;
  border-style: solid;
  float: left;
  width: 6.3rem;
}

footer {
  color: #fff;
  border-width:2px;
  border-style: solid;
  clear: both;
}

main {
  float: right;
  width: calc(100% - 7.2rem);
  padding: 5px;
  background: hsl(240, 100%, 50%);
}

main > article {
  background: hsl(240, 100%, 50%);
  background-image: url('https://source.unsplash.com/daily');
  color: hsl(240, 0%, 100%);
  border-width: 5px;
}

This is a small demonstration page, so we’ll style tags directly to aid readability rather than applying class naming systems.

We use floats to position the sidebar to the left and the main section to the right and we set the width of the sidebar to a fixed 6.3rem width. Then we calculate and set the remaining width for the main section using the CSS calc() function. The main section contains a gallery of items organized as vertical blocks.

A gallery of items organized as vertical blocks

The layout is not perfect. For example, the sidebar does not have the same height as the main content section. There are various CSS techniques to solve the problems but most are hacks or workarounds. Since this layout is a fallback for Grid, it will be seen by a rapidly diminishing number of users. The fallback is usable and good enough.

The latest versions of Chrome, Firefox, Edge, Opera and Safari have support for CSS Grid, so that means if your visitors are using these browsers you don’t need to worry about providing a fallback. Also you need to account for evergreen browsers. The latest versions of Chrome, Firefox, Edge, and Safari are evergreen browsers. That is, they automatically update themselves silently without prompting the user. To ensure your layout works in every browser, you can start with a default float-based fallback then use progressive enhancement techniques to apply a modern Grid layout. Those with older browsers will not receive an identical experience but it will be good enough.

The post Easy and Responsive Modern CSS Grid Layout appeared first on SitePoint.



Source link

The Real Problem With Pre-Made Themes


Designers, developers, site owners… lend me your eyeballs for a bit. There’s something rotten in the state of pre-made website themes. Alright, I’ve offended The Bard quite enough. But you get my point, right? Themes have gotten a bad rap for a variety of reasons: they can have bloated code, content must be designed to fit in them rather than designing them to fit the content, et cetera.

But they’ve also gotten really good. Many are made to be modular, so you only use and load the code you need. People have gotten a lot better at coding things to load fast, and there’s a theme for nearly every conceivable need. So maybe it’s not as optimized as it could be, if you’re not getting Amazon levels of traffic, regular hosting should be fine, right? And again, there’s a theme for every conceivable need! It’s just so convenient.

Wrong, wrong, wrong, (mostly) wrong.

Let me tell you a little story. A long, long time ago in February of 2018, I had an idea. Well, really I had a few ideas of things I desperately wanted to write about, but no one was paying me to do it. And honestly, keeping up a blog on the topics I had in mind wouldn’t be all that feasible. I like my projects to have a beginning, middle, end, and perhaps most importantly, a deadline.

So I thought, hey, why not make some niche/authority sites on these topics so dear to my heart? There’s no reason niche sites have to be predatory glorified ads with terrible aesthetics and UX. I could make them better. And I could just leave them up when I was done, with minimal updates. And hell, I don’t even need to design them! A wiki or knowledge base theme for WordPress or some other CMS would do quite nicely for my purposes.

I found plenty of themes…I very nearly dropped money on

And so I went theme hunting. I found plenty of themes in the categories I had in mind, including some absolutely beautiful premium themes I very nearly dropped money on. That would have been a terrible waste of my cash.

It’s because, you see, each and every one of these themes depended on JavaScript for their most basic functions: displaying any content at all, navigation, and search. (Now I told myself I wasn’t going to get back into this particular crusade. I told myself I could stop writing about how completely depending on JavaScript is a terrible idea. I wasn’t going to do this anymore, darnit!)

But people are getting ripped off, and I can’t stand for that. If you’re selling a theme that depends on JavaScript to work at all, you’re selling a site that is going to break under certain conditions. Whether it’s a slow connection, a plugin incompatibility, some ad network gone rogue, or a random browser hiccup, it’s going to break. If you allow a web product that’s intended for daily use to be that fragile, that’s an accessibility issue, and it’s a rip-off.

It’s one thing to build a JavaScript-dependent site for a client who knows the risks and chooses to take them. It is quite another to sell templates like that, especially without any warning. These things are only sometimes implemented by professional designers or developers who want to save time. They are very often implemented by beginners who are just learning a bit of HTML even as they use your theme.

More than that, these were wiki and knowledge base themes. Those are the kinds of sites people go to when they need help. Customer support and educational sites should be the least likely to break, period. This is a case where both the customer and the user are being let down in a big way.

People will always want flashy stuff, fine. We can’t help that fancy animation grabs the eye, and I don’t blame theme designers for using it as a selling point. But you owe it to your customers to implement fall-backs for every JavaScript element that might break. You owe it to them to at least make your basic layout, navigation, and any forms work under just about any condition. Ancient browsers notwithstanding.

you owe it to your customers to implement fall-backs for every JavaScript element that might break

In my mind, a lack of progressive enhancement, or at least graceful degradation, is the single biggest accessibility nightmare to plague the wonderful world of pre-made sites and themes. Customers are buying these things without knowing exactly what they’re doing, and it’s bound to end in misery. And here I thought bad planning was the biggest problem for theme-based sites.

Yes, implementing fall-backs for everything is difficult, but that’s why you charge money for these things. If they were all that easy to make, they could all be free, right? No, I don’t expect you to code your themes for every version of IE, and yes I realize that most premium themes come with support of some kind or another.

Theme authors just need to recognize that when JavaScript breaks, it most often only breaks for some of the end users, and only some of the time. But those end users could have turned into paying customers for the people who bought the themes, and now they probably won’t. And that’s on us designers and developers, no one else.

Well, now I have to go design my own wiki/knowledge-base style theme (probably for Grav CMS, at this point), because somebody needs to do it right, and it might as well be me. To quote Taylor Swift, “Look what you made me do.”

Add Realistic Chalk and Sketch Lettering Effects with Sketch’it – only $5!

Source

p img {display:inline-block; margin-right:10px;}
.alignleft {float:left;}
p.showcase {clear:both;}
body#browserfriendly p, body#podcast p, div#emailbody p{margin:0;}



Source link

Monthly Web Development Update 8/2018: The Cost Of JavaScript, Ethics In Open Source, And QUIC


Monthly Web Development Update 8/2018: The Cost Of JavaScript, Ethics In Open Source, And QUIC

Monthly Web Development Update 8/2018: The Cost Of JavaScript, Ethics In Open Source, And QUIC

Anselm Hannemann

2018-08-17T11:57:10+02:00
2018-08-17T10:16:34+00:00

Building technology and software has become a very responsible job. People trust the products we create, and they can have a significant impact on their lives, too. Considering this, we not only need to think about inclusive solutions, but also stand up and advocate for ethics, reliability, and security. It’s a position that gives us power.

Eric Meyer published an article elaborating the problems which an HTTPS-only web is bringing along. In it, he reveals that developing countries suffer a lot from this development as they often have bad internet connections and, due to the encryption, they now experience more website errors than before. Ben Werdmüller jumped in and published the article “Stop building for San Francisco” in which he points out one of the biggest problems we have as developers: We use privileged hardware and infrastructure. We build experiences using the latest iPhones, Macbooks with Gigabit or fast 4G connections but never consider that most people we’re building for use devices and infrastructures that are far from being that well-equipped. Making the web more secure is a great idea, beyond question, but we should also keep in mind the consequences that the latest tech and our design decisions might have for others.

News

General

UI/UX

  • Ethics for Design is a project where twelve designers and researchers from eight European cities discuss the, sometimes harmful, impact of design on our societies and what designers can do to work for the good of all and not just a few.

Tooling

  • Prashant Palikhe wrote a long story about the art of debugging with Chrome’s Developer Tools, which I can highly recommend as it’s a very complete reference to get to know the developer tools of a browser. If you use another browser, that’s not a big problem as most tools are quite similar.
  • WebP is an image format with a couple of nice features and likely one of the best-known new formats besides the common JPEG/PNG ones. However, creating WebP images can still be a challenge, so Jeremy Wagner wrote a guide on how to convert images to WebP.
  • Douglas Creager introduces the new Network Error Logging which allows you to instruct user agents to collect the same set of information that would appear in your server logs.
  • Many of us are addicted to communication tools like Slack. The folks from Wildbit decided to shut down Slack for a week — with a significant effect on how they work. An interesting case study about how we tend to get too comfortable with a useful tool and don’t use it as we should anymore. From time to time, it’s important to reset our minds.
  • Dennis Reimann published the first stable version of UIEngine, a workbench for UI-driven development.

Security

  • A new Observer is around: The ReportingObserver API lets you know when your site uses a deprecated API or runs into a browser intervention. So far, it’s available in Chrome 69. You could easily use this to send errors that previously were only available in the Console to your backend or error handling service.

Web Performance

HTTP request over QUIC
A QUIC handshake only takes a single round-trip between client and server to complete, whereas TCP and TLS usually need two. (Image source)

HTML & SVG

Accessibility

JavaScript

  • One year after they introduced their Progressive Web App, Zack Argyle from the Pinterest engineering team takes a look back. It’s important to note why they decided to build a PWA: “Our mobile web experience for people in low-bandwidth environments and limited data plans was not good”. But the results for them are amazing to see.
  • Philip Walton introduces the new Page Lifecycle API which helps us determine page states in the browser more easily via events, such as the page being in the background (not visible), active, frozen or even terminated.
  • Whoops, you all know eval() in JavaScript is bad, right? That’s why we usually forbid its usage in Content Security Policies. But Remy Sharp reminds us that there’s a line of code which is equally bad for security.
  • Addy Osmani researched the cost of JavaScript in 2018 and now shares evidence that every byte of JavaScript is still the most expensive resource we can send to mobile phones because it can delay interactivity significantly. This is a problem especially for not so capable phones that are widely used outside the tech industry.
  • Hidde de Vries explains how we can make page titles accessible in JavaScript Single Page Application.
The Cost Of JavaScript In 2018
What’s the real cost of JavaScript? One of the findings from Addy Osmani’s research: It takes a low-end 2018 phone 32 seconds longer than an iPhone 8 to process JavaScript for CNN.com. (Image source)

CSS

Work & Life

Going Beyond…

  • Tobias van Schneider wrote about why the Sagmeister-Walsh studio is so successful by staying small and why dreaming big but staying small is so important for creative thinking.
  • Ben Werdmüller shares his thoughts on how different it has become to start a business when you’re, for example, in San Francisco. This is a story where $117,000 are considered a “low income” in San Francisco and how this limits ideas.
  • Jeremy Nagel makes us think about the impact of our open-source code: As developers we tend to believe that making our code freely available is an amazing move but we forget that we make it available to bad players as well — to coal miners, to pollution-contributing companies, to those who use people to get rich while mistreating them, to those who rip you off indirectly. It’s not that you can’t do anything about it; you have to be aware of these issues and apply a better license or add a dedicated statement to your code.
  • India has a big plastic waste problem. Since a couple of months, a couple of fishers don’t ignore the plastic problem anymore but collect all the waste in their nets instead, and bring it back to the shore where it’s used to build roads. A great idea of making use of trash efficiently.
Smashing Editorial
(cm)



Source link

​Task management has never been easier


(This is a sponsored post.)

monday.com is a team management tool that is exceptionally suitable for any industry sector and by any sized team. It will perfectly serve a team of two or a team of hundreds spread around the globe, and it can manage multiple projects at once.

monday.com promotes effortless collaboration and transparency, it’s “cheetah fast,” it displays status in as many as 20 different colors, and its status board can be customized to fit your needs and your workflow.

It serves as an excellent alternative to having to force fit your work to meet the demands of your project management tools or systems.

Direct Link to ArticlePermalink

The post ​Task management has never been easier appeared first on CSS-Tricks.



Source link

Redesigning a Card-based Tumblr Layout with CSS Grid


In this tutorial we’re going to retrofit a grid-based design to a layout inspired by the What’re you into? Tumblr page, where the user can select a set of topics to tailor their recommended content.

The tumblr page

Only the visual design of the grid is executed, not the selection functionality, as shown in the Pen we’ll be building:

See the Pen MBdNav by SitePoint (@SitePoint) on CodePen.

The main goal is to implement the design with CSS Grid, but a fallback layout with floats is outlined in the Support section below.

Markup

Essentially, the page content consists of a list of cards:

<ul class="grid">
  <li class="card header">
    <h1>Which foods do you like?</h1>
    <p>Tell us what you crave for and we'll get you the tasty bits</p>
  </li>
  <li class="card">
    <a href="http://www.sitepoint.com/...">
      <h2>Pizza</h2>
      <img src="http://www.sitepoint.com/..." alt="A salami pizza">
    </a>
  </li>
  <!-- ... -->
</ul>

A card that represents a topic proposed to the user (food in our example) has a title and an illustrative image, both wrapped in a link element. Others could be adopted; see for instance the excellent article on the card component on Inclusive Components, where the pros and cons of such alternatives are analyzed.

Structural Layout

In this section, the foundations of the grid design will be implemented. The next section will style the cards. This Pen shows the bare-bones layout using placeholders for grid items. Run it on a browser that supports CSS Grid.

See the Pen JBqgGm by SitePoint (@SitePoint) on CodePen.

Before going ahead with the code, it’s important to specify the features and the responsive behavior of the grid. Let’s try to write down some properties it must satisfy.

Design Specs

Two kinds of cards are featured in the design: a series of topic cards, and an introductory cover card. We arrange them on an underlying grid composed of square cells of fixed size. Each topic card occupies just one of these cells, while the cover spans a larger area of adjacent cells, whose extent depends on the viewport width. Furthermore, rows and columns are separated by the same fixed-size gutter.

The underlying grid and the two card types

The grid has as many (fixed-sized) columns as they fit into the viewport:

Fixed sized columns that span the viewport width

But we don’t want a zillion columns on large screens, so let’s limit the maximum number of columns:

Limiting the number of columns

The columns are always horizontally centered in the viewport:

The columns are centered

Only the columns are centered, not the grid items. This means that the cards on an incomplete row are aligned to the left of the grid, not at the center of the viewport:

Center he columns, not the items

Check out these requirements in the above Pen. Also, it’s useful to inspect the layout with the CSS Grid tools provided by some browsers, such as the Firefox’s Grid Inspector.

Keeping in mind this checklist, we can fire up our favorite development environment and start coding.

Implementation

Let’s introduce a couple of Sass global variables to represent the layout parameters defined in the specs, namely:

  • $item-size for the size of the side of the grid cells
  • $col-gutter for the gutter between the tracks of the grid
  • $vp-gutter for a safety space to leave between the grid items and the viewport edges
  • $max-cols for the maximum number of columns the grid can have

We could use CSS custom properties for these variables, avoiding the need of a preprocessor and allowing us to edit them with the in-browser development tools and watch the changes happen instantly. But we’re going to use these values even for a fallback layout suitable for older browsers, where CSS variables aren’t supported. Moreover, we use expressions with these values even in media query selectors, where custom properties and the calc() function aren’t fully available even on recent browsers:

$item-size: 210px;
$col-gutter: 10px;
$vp-gutter: $col-gutter;
$max-cols: 5;

We must establish a grid formatting context on the grid element:

.grid {
  display: grid;
}

The grid-gap property separates the grid tracks by the specified amount of space.
But these gutters are only inserted between the tracks and not before the first track and after the last one. A horizontal padding on the grid container prevents the columns from touching the viewport edges:

.grid {
  grid-gap: $col-gutter;
  padding: 0 $vp-gutter;
}

The columns of the grid can be defined with the grid-template-columns property and the repeat function with the auto-fill value as the repetition number and the $item-size variable for the track list argument:

.grid {
  grid-template-columns: repeat(auto-fill, $item-size);
}

This tells the browser to fill the grid container (the .grid element) width with as many fixed-size columns as possible, keeping account of the vertical gutters.

It’s worth pointing out that we could have used the auto-fit mode, and in many combinations of viewport sizes and number of grid items we could not tell the difference with auto-fill. But when there are only a few items in the grid, with just an incomplete row, with auto-fit the items would be centered, instead of starting from the left of the grid, as detailed in the design specs. This happens because, while with auto-fill the grid has always as many columns as possible, with auto-fit empty columns are removed, and the centering of the remaining columns places the items at the center of the viewport:

If the first row of the grid is complete, no columns are removed and there’s no difference between the two modes:

No difference when there are several cards

Back to the grid columns. Up to this point, the number of columns had no limit. It can arbitrarily grow as the viewport width increases. But according to the spec, the grid must have a maximum number of columns. It’s possible to fix this with the max-width property:

.grid {
  max-width: grid-width($max-cols);
}

grid-width is a custom Sass function that returns the width of a grid with n columns:

@function grid-width($num-cols) {
  @return $num-cols * $item-size + ($num-cols - 1) * $col-gutter;
}

The first multiplication accounts for the size required by the columns, while the second one represents the space required by the gutters.

Relationship between columns and gutters

According to the specs, the grid must be always horizontally centered. We can combine the old auto margins trick with justify-content to accomplish this task:

.grid {
  justify-content: center;
  margin: 40px auto;
}

justify-content centers the columns when there’s available space left inside the grid container. This happens when the container bleeds from one viewport edge to the other. The lateral auto margins center the .grid container itself when it has reached its maximum width.

Now for the rows. They’re not explicitly specified, as done with the columns. Rather, they’re implicitly added by the browser as needed, and we just tell it their size with the grid-auto-rows property. Reusing the $item-size variable, each grid cell is shaped like a square, as per the specs:

.grid {
  grid-auto-rows: $item-size;
}

Let’s move on by sizing the cards. On small viewports, when the grid configures itself on a single column, the cover card spans only a grid cell, while when there are two or more columns, it must span a 4×4 grid area:

@include when-n-cols(2) {
  .grid .header {
    grid-row: span 2;
    grid-column: span 2;
  }
}

when-n-cols() is a Sass mixin to express a media query suitable for a grid with the given number of columns:

@mixin when-n-cols($n) {
  @media screen and (min-width: #{grid-width($n) + 2 * $vp-gutter + $scrollbar-size}) {
    @content;
  }
}

The CSS rules represented by @content are active whenever the viewport width is equal or greater than the width of a grid with $n columns plus the two safety spaces to separate the grid items from the viewport edges. $scrollbar-size is just an upper bound on the size of a vertical scrollbar, to account for the fact that the width reported in the media query is the entire viewport width, including an eventual vertical scrollbar.

Regarding the topic cards, there’s nothing to do, because the default Grid behavior makes them the same size as their assigned grid cells.

Okay, we got it! Refer to the structural Pen at the beginning of this section to see all these code snippets put together in the complete code.

The post Redesigning a Card-based Tumblr Layout with CSS Grid appeared first on SitePoint.



Source link