Wszystkie wpisy, których autorem jest admin

How to Start Your Business Using Only WordPress and These 10 Tools

Post pobrano z: How to Start Your Business Using Only WordPress and These 10 Tools

Starting an online business might seem a little overwhelming at times. There are a lot of questions that will pop into your head: “where do I start?”, “how do I measure my results?”, “how do I create and manage my content?”

You’d be surprised how easy and simple it can actually be – with the right tools, of course.

We’ve found these 10 amazing tools that will be the only thing you need when combined with WordPress: marketing automation, Instagram followers, file storage, and much more will be taken care off in a glimpse.

1. Integromat

No WordPress page can go without a good cloud workflow automation – with all the plugins, apps and tools you already use, this one will make the process so much faster. All needed automation is created through a beautifully designed editor. You can choose from many pre-made templates that integrate perfectly with WordPress.

2. pCould

There are multiple dropbox alternatives on the internet – but if you’re a WordPress user and value security and speed, then this is the only option for you. Other than these two advantages of security and speed, the tool also lets you share your files with your colleagues which is highly convenient.

3. MaxTraffic

Sending web push notifications is one of the best strategies for bringing a customer back to a WordPress website. Keep your customers alert and waiting: send them notifications about new products and services, sales or upcoming events – make the visits to your website spike up.

4. Combin

If you have a plan to start a business, you probably already know, that after creating a website, a WordPress platform is not enough – you will have to do something with marketing and especially social media. Get real Instagram followers by using Combin – like, comment, and follow other users to attract their attention.

5. Focused Collection

Visual information is crucial for any website nowadays. To represent our brand, we often use stock photos – there is a wide selection of free and paid stock images around the web. The focused collection is something new and different – it has complete sets of pictures for different themes like animals, cities, education and more. Perfect for creating a strong image of the brand.

6. Word Counter

WordPress is an amazing platform for content creation – it has various content and SEO tools to help you out, but one important tool that you just cannot go without is a very precise word counter. This one has a minimalistic design, is easy to use and understand, and also has integrated social media standards for word count.

7. InvoiceNinja

After starting an online business you will have to step up your game and start working with your potential clients – collecting their emails by offering them something of value in return and reaching them with your news and sales. Proposals creation tool can help you reach your customer – the drag & drop tool offers great templates to make it look great. And later it can help you send the invoice from anywhere, after all the name is InvoiceNinja.

8. Magic Password

This WordPress Security Plugin can work wonders when it comes to remembering passwords and usernames. This plugin also protects you from brute-force attacks, phishing & keylogger attacks, and WordPress website takeover. The tool works by pairing your smartphone with your WordPress account and creating a specific code when you need to log in.

9. Omnisend

Omnisend is an ideal tool for WordPress ecommerce marketing automation if you want to run an e-shop. It can make the work with the website visitors so much easier: turn them into subscribers with signup boxes, popups, and landing pages. Afterward, start working your way up by converting your subscribers into shoppers and eventually – repeat buyers.

10. Salesmate

Salesmate is one of the best additional tools for WordPress – if you want to run an e-shop, it will work wonders by helping you plan and keep on track with your sales processes. It’s easily customizable and adjustable, therefore easy to use and integretable with more than 700 different apps.

SOS Children’s Villages Belgium: Really Ugly Sweater

Post pobrano z: SOS Children’s Villages Belgium: Really Ugly Sweater

Media
SOS Children’s Villages Belgium

There are ugly Christmas sweaters. And there’s the #reallyuglysweater. Take a closer look at it and you’ll see: the normally oh-so-peaceful crib is being bombed in the midst of a Syrian refugee camp. An ugly but very real scene for all those struggling in Syria on a daily basis. Gents created the fashion statement of the year to showcase the other side of the holidays and to ensure a truly merry Christmas for all children. One ugly sweater at a time. More than 10.000 eur was raised to support the work of SOS Children’s Villages in Syria.

Advertising Agency:Gents Agency, Gent, Belgium
Chief Executive Officer:Leen Van der Mijnsbrugge
Creative Director:Tim Helsen
Creative Strategy Director:Sander Vanermen
Senior Creative:Vincent Daenen
Creative Strategist:Janne Van Robays
Interactive Design Director:Simon Pertz
Senior Web Architect:Diederik Van Hoorebeke
Senior Interactive Designer:Thomas Heylen
Senior Designer:Martijn Leenaers
Account Director:Julie Bataillie
Account Manager:Albane Paret

Home Office: Ben, Aliya, Sonny

Post pobrano z: Home Office: Ben, Aliya, Sonny

Film
Home Office

Advertising Agency:FCB Inferno, London, United Kingdom
Executive Vice President:Sharon Jiggins
Creative Partner:Al Young
Chief Strategy Officer:Vicki Holgate
Creative Directors:Ben Edwards, Guys Hobbs
Account Director:Emily Whiteaway
Senior Account Manager:Jamie Tomkins
Account Manager:Lara Ashman
Producer:Charlie Coombes
Senior Project Manager:Tom Lawrence
Senior Strategist:Laura Pirkis
Strategist:Lucie Newlan
Lead Designer:Adam Booker
Account Executive:Sian Pearson
Artworkers:Rich Bagley, Steve Clark
Digital Designer:Chris Jordan
Director:James Burns
Production House:Archers Mark

Handicap International: #BodyCantWait

Post pobrano z: Handicap International: #BodyCantWait

Outdoor
Handicap International

Advertising Agency:Herezie Group, Paris, France
Chief Operating Officer:Pierre Callegari
Chief Executive Officer:Andrea Stillacci
Executive Creative Director:Baptiste Clinet
Creatives:Joseph Dubruque, Axel Didon, Raphael Stein
Art Director Assistant:Cyril Haoual
Tv Producer:Barbara Vaira
Account Director:Laurence Cornet
Account Manager:Marion Leroy
Pr:Anne Rabasse, Kim Ball
Production Company:La\Pac, Paris)
Producer:Anna Roudaut
Executive Producer:Chris Ellis
Directors:Guillaume Cagniard, Hossegor, Virgile Texier, Hossegor
DoP:Anaïs Andreassian
Steadycamer:Thomas Burgess
Camera Assistant:Xavier Vito
Model Maker:Bruno Villedieux
Music:Lorenzo Esposito Fornasari, Eraldo Bernocchi

BMW: X5 Experiment

Post pobrano z: BMW: X5 Experiment

Film
BMW

In a country that loves its bobsleigh, at a time when all eyes are on the Olympic contestants, we took four adventurous people on a truly epic ride. Virtual reality meets a comfy BMW X5, with a champion racing driver behind the wheel – to give passengers all the adrenaline of an Olympic bobsleigh run.

Advertising Agency:DDB, Latvia
Creative Director:Vairis Strazds
Account Director:Nora Kirta
Producer:Ance Jēkabsone
Copywriter:Marta Kukarane
Digital Strategy:Dāvis Freibergs
Video Editor:Aivars Katkovskis
Creative:Sintija Popena
Production:DDB Latvia, Robyworks, Kind.Lv

Compressive Images Revisited

Post pobrano z: Compressive Images Revisited

Tim Kadlec returns to the topic of how to make images on the web as performant as possible and looks at the technique called “Compressive Images” which is now not recommended for a bunch of reasons. Tim summarizes his point here:

By now the trade-off is pretty clear. Compressive images give us a reduced file size, but it greatly increases the memory footprint. Thanks to the standards that have been developed around responsive images, it’s a trade-off we no longer need to make.

If you’re interested in learning more then it’s hard not to recommend Jason Grigsby’s masterclass called Responsive Images 101, too.

Direct Link to ArticlePermalink

The post Compressive Images Revisited appeared first on CSS-Tricks.

How to Draw a Tree

Post pobrano z: How to Draw a Tree

Final product image
What You’ll Be Creating

Trees are beautiful embodiments of nature’s abundance and variety. They can live for many years; the oldest tree ever discovered is approximately 5,000 years old. No wonder that artists of all skill levels are attracted to trees, trying to convey their charm and diversity. 

In this tutorial, I’ll show you how to draw a typical tree, using graphite pencils. But first, we need to observe some basic things, like constructing a branch with twigs, creating an illusion of foliage, and drawing the bark.

Let’s dive into the world of nature and have fun!

You may also be interested in these tutorials on drawing trees and leaves:

What You Will Need

You will need the following supplies to create this project:

  • an HB graphite pencil
  • a 3B graphite pencil
  • an eraser
  • drawing paper
The art supplies for this project

1. How to Draw Bark

Step 1

What is commonly called bark includes a number of different tissues that overlay the wood and serve as a protective barrier. For example, cork is an external tissue that is impermeable to water and gases.

Why do we start with this part of the tree? Bark is a concluding element that covers the shape of the trunk and branches. Knowing how to draw bark will speed up our process later on, when we gain an understanding of designing a tree from scratch.

Let’s draw just a sample of the tree bark in close-up; we’ll focus on its pattern and details. With an HB pencil, I draw a small rectangle and fill it with lines that imitate the bark’s pattern.

Don’t overthink this pattern in the early stages; just draw something resembling irregular rhombs.

Drawing the main contours of the pattern

Step 2

I add more details to the drawing, using the HB pencil. The groups of parallel hatches help to create the illusion of a three-dimensional surface.

Adding the details to the pattern

Step 3

With the 3B pencil, I darken the borders between the sections of bark. You can also use dots to make the texture more interesting.

Adding depth to the pattern

Step 4

With the 3B pencil, I decrease the contrast, covering the sample with a layer of soft, smooth hatching. Then I accentuate the shadows once again. This sample is complete!

Completing the sample

Step 5

Let’s create another sample of the bark texture; this time I draw larger shapes, using the HB pencil. I also add areas of moss and cover them with a layer of hatching.

Creating the pattern of lines

Step 6

With the HB pencil, I add some shadows to the moss and the bark.

Creating the shadows

Step 7

With the 3B pencil, I increase the contrast in the drawing, accentuating the borders between the sections and under the moss.

Increasing the contrast

Step 8

I add more details with dots and short hatches, using the 3B pencil. I also darken the perimeter of the sample to create an illusion of depth.

Completing the second sample

2. How to Draw a Branch

Step 1

A branch is a woody element that is connected to the central trunk of a tree. Large branches are known as boughs, and small branches are known as twigs or sprigs.

Branches and twigs may be found in many different shapes and sizes; while branches can be nearly horizontal, vertical, or diagonal, the majority of trees have upwardly diagonal branches.

Let’s draw a standard branch; I mark its core line with the HB pencil. It’s also useful to mark the place where the branch connects to the trunk.

Drawing the core line of the branch

Step 2

I draw the form of the branch. Remember that it is a three-dimensional shape with a round foundation.

Adding the shape of the branch

Step 3

I erase the subsidiary lines and refine the contour of the branch.

Creating a new contour with an organic line

Step 4

I add the smaller branches. Feel free to add as many of them as you wish, and make them diverse.

Adding the smaller branches

Step 5

I add tiny twigs.

Adding the twigs

Step 6

I draw the leaves; they capture light energy and convert it into sugars by photosynthesis, providing the food for the tree’s growth and development.

Make sure that the leaves in your drawing have different sizes and directions. Usually, we don’t see each leaf as an individual element, but for the sake of our study let’s allow a hint of stylization.

Drawing the leaves

Step 7

I add the long lines and the groups of hatching, imitating the bark texture. It’s so great that we already know how to draw bark, isn’t it?

Creating the rough pattern of the bark

Step 8

With the 3B pencil, I darken the sides of the branch to make it three-dimensional. I also fill the space around the leaves with groups of hatches to create an illusion of depth.

Increasing the contrast and completing the drawing

3. How to Draw a Tree

Step 1

Now we are ready to draw the whole tree. I mark the foundation of the tree and add the core line.

Drawing the core line of the tree and its basis

Step 2

A tree usually has a wide foundation and a thin top. I construct the shape of the tree, creating the segments of the shape and joining them together with a pencil contour.

Drawing the shape of the tree

Step 3

I add the shapes of the branches; they differ in size and direction.

Adding the branches

Step 4

I erase the subsidiary lines and refine the contour. When it comes to the natural objects, small imperfections are charming!

Refining the contour lines

Step 5

I add the smaller branches and twigs, based on the principles that we observed in the previous part of the tutorial.

Drawing the branches and twigs

Step 6

Since we are drawing a whole tree, there is no point in representing every single leaf. I add rough shapes of the leaves just to the lower branches and the bounds of the crown.

It’s important to keep the shapes sketchy; too many details will make your drawing look weird and unnatural.

Adding the shapes of the individual leaves

Step 7

Let’s create an illusion of foliage. An easy way to draw masses of leaves is to fill the crown with scribble lines. You can find an example of this technique in the lower corner of the illustration below.

With the HB pencil, I cover the area of the crown with scribble-like lines, leaving some areas lighter and darkening the underside of the crown.

Creating an illusion of foliage

Step 8

It’s time to work on the trunk; it usually is darker than the foliage, so having the right contrast is vital.

With the HB pencil, I draw the rough pattern of the bark and mark the core shadows. Please note that we see this pattern from a distance, so having much detail here won’t be a help.

I also decided to bring in a cute addition: a hollow with an owl that is looking out. 

Working on the trunk

Step 9

With the 3B pencil, I increase the contrast in the drawing. Feel free to make the sides of the tree and the visible parts of the branches really dark.

Darkening the trunk with a soft pencil

Step 10

With the 3B pencil, I darken the foliage, accentuating the lower part of the crown. The goal here is to achieve a contrasting yet harmonious look.

I complete the drawing by adding some grass near the base of the trunk.

Adding the details and completing the drawing

4. How to Draw a Tree Stump

Step 1

With the HB pencil, I draw the core line and the foundation of the stump.

Drawing the foundation and core line of the stump

Step 2

I add the top section of the stump. The core line may be a useful reference tool, but you don’t have to make this shape perfectly even.

Completing the shape of the stump

Step 3

I mark the texture of the bark, using the HB pencil.

Adding the texture of the bark

Step 4

A transverse section through a tree trunk may show concentric circles of lighter and darker wood—the tree rings (also known as the annual growth rings). These circles usually have a regular shape, but sometimes, due to abnormal growth conditions, they turn into wavy joint lines.

I mark the center of the inner part of the trunk, and then draw circular shapes going from the section’s center to the periphery. I also add small cracks to make the drawing more credible.

Working on the top part of the stump

Step 5

With the HB pencil, I create the texture of the bark. I also add horizontal hatches to the top section of the stump to accentuate its flat plane.

Working on the texture

Step 6

I darken the sides of the stump, using the 3B pencil. It’s time to add details to the bark, like small islets of moss, and to vary the pattern of the growth rings.

The top plane of the stump may demonstrate interesting transitions from a darker core to a lighter periphery (which proceeds to a slightly darker area near the bark).

Making the shape three-dimensional

Step 7

The drawing of the stump itself is complete, but it doesn’t look believable. I add some grass and fern leaves to create a nice natural environment.

Completing the drawing

Your Drawings Are Complete

Congratulations—we’ve created four beautiful graphite pencil sketches! I hope you were inspired by the trees and enjoyed the process of drawing.

Let your creative journey be fruitful and full of joy!

The result of work

React Code Style Guide

Post pobrano z: React Code Style Guide

I’ve been having the time of my life with React lately. But on my journey, I’ve had a hard time finding good code style guidelines to keep the mix of JSX and JS clean and readable. I’ve been coming up with my own style guides that I’d love to share. Maybe these will be useful to you and, of course, feel free to share similar guidelines in the comment thread below.

Rule #1: Destructure your props

One of my favorite ES6 features is destructuring. It makes assigning object properties to variables feel like much less of a chore. Let’s take a look at an example.

Say we have a dog that we want to display as a div with a class named after its breed. Inside the div is a sentence that notes the dog’s color and tells us if it’s a good dog or bad dog.

class Dog extends Component {
  render () {
    return <div className={this.props.breed}>My {this.props.color} dog is {this.props.isGoodBoy ? "good" : "bad"}</div>;
  }
}

That technically does everything we want, but it just seems like quite a big block of code for what really is only three variables and one HTML tag.

We can break it out by assigning all of the properties of props to local variables.

let breed = this.props.breed;
let color = this.props.color;
let isGoodBoy = this.props.isGoodBoy;

Using ES6, we can put it in one clean statement like this:

let { breed, color, isGoodBoy } = this.props;

To keep everything clean, we put our ternary operator (more on that later) in its own variable as well, and voila.

class Dog extends Component {
  render () {
    let { breed, color, isGoodBoy } = this.props;
    let identifier = isGoodBoy ? "good" : "bad";
    return <div className={breed}>My {color} dog is {identifier}</div>;
  }
}

Much easier to read.

Rule #2: One tag, one line

Now, we’ve all had that moment where we want to take our entire function and make it a mash of operators and tiny parameter names to make some uglified, superfast, unreadable utility function. However, when you’re making a stateless Component in React, you can fairly easily do the same thing while remaining clean.

class Dog extends Component {
  render () {
    let { breed, color, goodOrBad } = this.props;
    return <div className={breed}>My {color} dog is {goodOrBad}</div>;
  }
}

vs.

let Dog = (breed, color, goodOrBad) => <div className={breed}>My {color} dog is {goodOrBad}</div>;

If all you’re doing is making a basic element and placing properties in an HTML tag, then don’t worry about making such a big deal of all the functions and wrappers to get an entirely separate class going. One line of code will do.

You can even get creative with some ES6 spread functions if you pass an object for your properties. Using this.props.content will automatically put the string between the open and close tag.

let propertiesList = {
  className: "my-favorite-component",
  id: "myFav",
  content: "Hello world!"
};
let SimpleDiv = props => <div {... props} />;

let jsxVersion = <SimpleDiv props={propertiesList} />;

When to use the spread function:

  • No ternary operators required
  • Only passing HTML tag attributes and content
  • Can be used repeatedly

When not to use the spread function:

  • Dynamic properties
  • Array or object properties are required
  • A render that would require nested tags

Rule #3: The rule of 3’s

If you have three or more properties, then put them on their own line both in the instance and in the render function.

This would be fine to have just one line of properties:

class GalleryImage extends Component {
  render () {
    let { imgSrc, title } = this.props;
    return (
      <figure>
        <img src={imgSrc} alt=React Code Style Guide />
        <figcaption>
          <p>Title: React Code Style Guide</p>
        </figcaption>
      </figure>
    );
  }
}

But consider this:

class GalleryImage extends Component {
  render () {
    let { imgSrc, title, artist, clas, thumbnail, breakpoint } = this.props;
    return (
      <figure className={clas}>
        <picture>
          <source media={`(min-width: ${breakpoint})`} srcset={imgSrc} />
          <img src={thumbnail} alt=React Code Style Guide />
        </picture>
        <figcaption>
          <p>Title: React Code Style Guide</p>
          <p>Artist: {artist}</p>
        </figcaption>
      </figure>
    );
  }
}

Or the render:

<GalleryImage imgSrc="./src/img/vangogh2.jpg" title="Starry Night" artist="Van Gogh" clas="portrait" thumbnail="./src/img/thumb/vangogh2.gif" breakpoint={320} />

It can get to be too much of a codeblock to read. Drop each property to the next line for a clean, readable look:

let { imgSrc,
      title,
      artist,
      clas,
      thumbnail,
      breakpoint } = this.props;

and:

<GalleryImage
  imgSrc="./src/img/vangogh2.jpg"
  title="Starry Night"
  artist="Van Gogh" 
  clas="landscape"
  thumbnail="./src/img/thumb/vangogh2.gif"
  breakpoint={320} />

Rule #4: Too many properties?

Property management is tricky at any level, but with ES6 destructuring and React’s state-based approach, there are quite a few ways to clean up the look of a lot of properties.

Let’s say we’re making a mapping application that has a list of saved addresses and a GPS coordinate for your current location.

The current user information of position and proximity to favorite address should be in the parent Component of App like this:

class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      userLat: 0,
      userLon: 0,
      isNearFavoriteAddress: false
    };
  }
}

So, when we make an address and we want it to note how close you are to the address, we’re passing at least two properties from App.

In App render ():

<Address
  ... // Information about the address
  currentLat={this.state.userLat}
  currentLong={this.state.userLon} />

In the render function for Address Component:

render () {
  let { houseNumber,
        streetName,
        streetDirection,
        city,
        state,
        zip,
        lat,
        lon,
        currentLat,
        currentLon } = this.props;
  return ( ... );
}

Already, you can see how this is getting unwieldy. If we take the two sets of information and break them out into their own objects, it becomes much more manageable.

In our App constructor ():

this.state = {
  userPos: {
    lat: 0,
    lon: 0
  },
  isNearFavoriteAddress: false
};

At some point before App render ():

let addressList = [];
addressList.push({
  houseNumber: "1234",
  streetName: "Street Rd",
  streetDirection: "N",
  city: "City",
  state: "ST",
  zip: "12345",
  lat: "019782309834",
  lon: "023845075757"
});

In App render ():

<Address addressInfo={addressList[0]} userPos={this.state.userPos} />

In the render function for Address Component

render () {
  let { addressInfo, userPos } = this.props;
  let { houseNumber,
        streetName,
        streetDirection,
        city,
        state,
        zip,
        lat,
        lon } = addressInfo;
  return ( ... );
}

Much, much cleaner. React also has some great ways to ensure that object properties exist and are of a certain type using PropTypes that we don’t normally have in JavaScript, which is just a great OOP thing anyway.

Rule #5: Dynamic renders – Mapping out arrays

Quite often in HTML, we’re writing the same basic pieces of code over and over, just with a few key distinctions. This is why React was created in the first place. You make an object with properties that return a complex, dynamic HTML block, without having to write each part of it repeatedly.

JavaScript already has a great way to do lists of like information: arrays!

React uses the .map() function to lay out arrays in order, using one parameter from the arrays as a key.

render () {
  let pokemon = [ "Pikachu", "Squirtle", "Bulbasaur", "Charizard" ];
  return (
    <ul>
      {pokemon.map(name => <li key={name}>{name}</li>)}
    </ul>
  );
}

You can even use our handy-dandy spread functions to throw a whole list of parameters in by an object using Object.keys() (keeping in mind that we still need a key).

render () {
  let pokemon = {
    "Pikachu": {
      type: "Electric",
      level: 10
    },
    "Squirtle": {
      type: "Water",
      level: 10
    },
    "Bulbasaur": {
      type: "Grass",
      level: 10
    },
    "Charizard": {
      type: "Fire",
      level: 10
    }
  };
  return (
    <ul>
      {Object.keys(pokemon).map(name => <Pokemon key={name} {... pokemon[name]} />)}
    </ul>
  );
}

Rule #6: Dynamic renders – React ternary operators

In React, you can use operators to do a conditional render just like a variable declaration. In Rule #1, we looked at this for stating whether our dog was good or bad. It’s not entirely necessary to create an entire line of code to decide a one-word difference in a sentence, but when it gets to be large code blocks, it’s difficult to find those little ?’s and :’s.

class SearchResult extends Component {
  render () {
    let { results } = this.props;
    return (
      <section className="search-results">
        {results.length > 0 &&
          results.map(index => <Result key={index} {... results[index] />)
        }
        {results.length === 0 &&
          <div className="no-results">No results</div>
        }
      </section>
    );
  }
}

Or, in true ternary fashion

class SearchResult extends Component {
  render () {
    let { results } = this.props;
    return (
      <section className="search-results">
        {results.length > 0
          ? results.map(index => <Result key={index} {... results[index] />)
          : <div className="no-results">No results</div>
        }
      </section>
    );
  }
}

Even with our tidy result mapping, you can see how the brackets are already nesting quite densely. Now, imagine if our render had more than just one line. It can pretty quickly get unreadable. Consider an alternative:

class SearchResult extends Component {
  render () {
    let { results } = this.props;
    let outputJSX;
    if (results.length > 0) {
      outputJSX = (
        <Fragment>
          {results.map(index => <Result key={index} {... results[index] />)}
        </Fragment>
      );
    } else {
      outputJSX = <div className="no-results">No results</div>;
    }
    return <section className="search-results">{output}</section>;
  }
}

Ultimately, the code length is about the same, but there is one key distinction: with the first example, we’re rapidly switching back and forth between two different syntaxes, making visual parsing taxing and difficult, whereas the second is simply plain JavaScript with value assignments in one, consistent language and a one-line function return in another.

The rule of thumb in this situation is that if the JavaScript you’re putting into your JSX object is more than two words (e.g. object.property), it should be done before the return call.

Wrap up

The combination of syntax can get messy, and these are the most obvious situations where I saw my code going off the rails. Here are the basic concepts that these all come from and can be applied to any situation that wasn’t covered here:

  • Use ES6 features. Seriously. There are a lot of fantastic features that can make your job easier, faster, and much less manual.
  • Only write JSX on the right side of an = or a return.
  • Sometimes you need JavaScript in your JSX. If your JavaScript doesn’t fit on one line (like a .map() function or ternary operator), then it should be done beforehand.
  • If your code starts looking like (<{`${()}`} />), then you’ve probably gone too far. Take the lowest level outside the current statement and do it before this one.

The post React Code Style Guide appeared first on CSS-Tricks.

A CSS Approach to Trap Focus Inside of an Element

Post pobrano z: A CSS Approach to Trap Focus Inside of an Element

I recently read this article by Keith Grant which introduced the newly arrived <dialog>. Excited by this new UI element, I immediately sat down to experiment with it to see how it can be used effectively as a modal — the most common use of it. While experimenting, I discovered a neat CSS trick on how to trap focus within the <dialog> element, a common accessibility requirement for modals, and a notoriously difficult one.

Disclaimer: The <dialog> demos in this article are tested on Chrome and Firefox browsers only. Safari has some weird issue where not all elements are focused while doing a normal keyboard navigation with Tab key!

What is focus trapping?

First, a quote from the W3C documentation regarding what should happen following a key press inside a dialog:

Tab:

  • Moves focus to the next tab-able element inside the dialog.
  • If focus is on the last tab-able element inside the dialog, moves focus to the first tab-able element inside the dialog.

Shift + Tab

  • Moves focus to the previous tab-able element inside the dialog.
  • If focus is on the first tab-able element inside the dialog, moves focus to the last tab-able element inside the dialog.

To summarize, when inside a dialog, pressing Tab or Shift+Tab should cycle the focus within the dialog only—amongst the focusable elements inside the dialog.

This makes sense because when a dialog is open, a user is interacting only inside it and allowing the focus to escape outside the dialog would essentially be mixing contexts and possibly create a state where the user doesn’t know which element is in focus.

So, going back to the idea of a modal, our expectation would be that tabbing inside of the modal would only focus on elements inside of the modal. Anything outside of the context of the modal would be out of scope because the tab is only concerned with what is inside of it. This is what we mean by focus trapping.

An implementation with JavaScript

If we were to implement focus trapping inside a <dialog>, the most common approach would be to do the following when the dialog opens:

1. Grab all the focusable/tappable elements inside the dialog.
2. Listen for Tab and Shift+Tab keypresses and manually focus the next or previous element, respectively.
3. If the keypress happens on the first focusable element, then focus the last focusable element in the chain and vice versa.

This way, we create a loop on focus as the user presses Tab or Shift+Tab. See this W3C code snippet as an an example of how this might be approached with JavaScript. You’ll see it’s quite a bit of JavaScript.

Enter :focus-within

Back to my experiment with the new <dialog> element. When thinking about focus trapping, a CSS pseudo class (also very recent in browsers) immediately came to my mind : :focus-within.

If you have not heard about that before, it represents an element that has received focus or contains an element that has received focus. So, for example, you have a <div> and inside of it is an input element. If you want to style that <div> when the contained input has focus, you can do it like so:

div:focus-within {
 border: 2px solid red;
}

See the Pen :focus-within by Geoff Graham (@geoffgraham) on CodePen.

The CSS trick to focus trapping

Let’s exploit :focus-within and CSS transitions to implement a basic focus trap inside of a <dialog> element.

To summarise, here is how the trick works. When the focus is not within the dialog (and the dialog is open), we:

  1. trigger a CSS transition
  2. detect that transition completion in JavaScript
  3. focus the first element in the dialog

But, first let’s get set up. Here’s the basic dialog and opening functionality:

<button id="button">Open dialog</button>
<dialog id="modal">
  <form action="">
    <label>
      <input type="text" /> Username
    </label>
    <label>
      <input type="password" /> Password
    </label>
    <input type="submit" value="Submit" />
  </form>
</dialog>
button.onclick = () => {
  modal.showModal();
}

There we go. Clicking on the button should open our dialog. Just this much code required to make a basic working modal using the new <dialog> element!

See the Pen Dialog without focus trap by Kushagra Gour (@chinchang) on CodePen.

Note: As in the above example demo of dialog, you’ll notice some extra polyfill code to make <dialog> work in browsers where it isn’t supported.

If you opened the dialog in the example above and started tabbing several times, you may have already noticed the problem: the focus starts with elements in the dialog, but then leaves once the last element in the dialog has been passed.

This is the core of our trick. We somehow need to send the lost focus detected with :focus-within over to JavaScript so that we can send the focus back to the dialog. This is where CSS transitions come into play. A CSS transition is something that happens through CSS, but emits events in JavaScript too. In our case, we can trigger a transition on any property with a negligible (because it doesn’t matter in our case) visual difference and listen for the transition completion in JavaScript.

Note that we need to trigger this transition when the dialog is open but doesn’t have focus inside it.

dialog {
  background-color: rgb(255, 255, 255);
}
dialog[open]:not(:focus-within) {
  background-color: rgb(255, 255, 254);
  transition: background-color 0.01s;
}

Let’s see what that CSS is doing.

  1. We put a background-color of our choice on the dialog. This isn’t necessary, but ensures we have the same background color across browsers.
  2. The dialog[open]:not(:focus-within) selector applies when the dialog is open but doesn’t have focus on or inside it. This works because native <dialog> element puts an open attribute when it’s open.
  3. Inside this rule, we change the background-color by a minimum amount. This is the least change required to trigger a CSS animation and at the same time not causing any visual difference for the user (remember this is a dummy transition). Also, we set the transition property with a very small duration because we want it to finish as soon as possible and get detected in JavaScript.

A touch of JavaScript

Now, all we need to do is detect the end of our triggered CSS transition and focus back the first element inside the modal, like so:

modal.addEventListener('transitionend', (e) => {
  modal.querySelector('input').focus();
});

We attach a transitionend listener on the modal and inside the callback, we focus the first input inside the modal. Done!

See the Pen Dialog focus trapping with CSS by Kushagra Gour (@chinchang) on CodePen.

Limitations

This is a quick experiment I did to create a working proof-of-concept of focus trapping with the :focus-within pseudo class. It has several limitations compared to dedicated JavaScript solutions to achieve this. Nevertheless, something is better than nothing!

Here are a couple of things this implementation lacks:

  1. According to W3C guidelines, the focus should cycle on the focusable element. But we are always focusing on the first input element. This is because without writing more JavaScript, we cannot know whether the focus was lost from the first or last element.
  2. We are always focusing back to the first input element. But there are many more focusable HTML elements that might be present before input or maybe there is not input element at all inside the modal. Again, full-fledged JavaScript solutions detect and maintain a list of all focusable elements and focus the right one.

Better (JavaScript) implementations of focus trapping

  1. As mentioned earlier, one working example is available inside the W3C documentation itself.
  2. Here is another implementation by Rodney Rehm that also listens for tab.
  3. Greg Kraus has a library that achieves this. His implementation maintains a list of selectors for all valid focusable elements.
  4. One more lightweight library to create accessible modals.

That is all for this experiment. If you liked this trick, you can follow me on Twitter where I share more articles and side projects of mine.

The post A CSS Approach to Trap Focus Inside of an Element appeared first on CSS-Tricks.