emGee Software Solutions Custom Database Applications

Share this

Tuts+ Code - Web Development

Updated: 6 days 14 hours ago

Preview Our New Course on Angular Material

Wed, 01/09/2019 - 05:50

Angular Material makes it easy to create a great UI for your Angular app. See how it works in our new course, Building App UIs With Angular Material. Keep reading for some free videos from the course.

What You’ll Learn

In this course, Dan Wellman will show you how to use Angular and Angular Material to build rich and interactive UIs for your web apps. You'll learn how to set up the library in a new project and how to use each of the main interface components and layout components. You'll also learn how to create forms and use overlay components such as dialogs and tooltips.

Here are a couple of free lessons from this course, as a preview of what you can expect:

Adding Your First Material Component

In this video, you'll learn how to add your first Material component, which will be the Material sidebar component. This is one of the components that you can generate using the Angular CLI, so it makes sense to start here.

 Material Form Fields

In this video, you'll learn about the Material form field container, which is the basis for creating styled and dynamic form controls using Angular Material.

 Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 870,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Categories: Web Design

Build Your Own CAPTCHA and Contact Form in PHP

Tue, 01/08/2019 - 09:11

People write code every day to automate a variety of processes. We exploit the fact that computers are a lot faster and more accurate than humans, which lets us simplify a lot of mundane tasks. Unfortunately, these same abilities can be used to program computers to do something malicious like sending spam or guessing passwords. The focus of this tutorial will be on combating spam.

Let's say you have a website with a contact form to make it easy for visitors to contact you. All they have to do is fill out a form and hit the send button to let you know about a problem or request they have. This is an important feature of a public-facing website, but the process of filling out form values can be automated by malicious users to send a lot of spam your way. This type of spamming technique is not limited to just contact forms. Bots can also be used to fill your forums with spam posts or comments that link to harmful websites.

One way to solve this problem is to devise a test which can distinguish between bots which are trying to spread spam and people who legitimately want to contact you. This is where CAPTCHAs come in. They generally consist of images with a random combination of five or six letters written on a colored background. The idea is that a human will be able to read the text inside the image, but a bot won't. Checking the user-filled CAPTCHA value against the original can help you distinguish bots from humans. CAPTCHA stands for "completely automated public Turing test to tell computers and humans apart".

In this tutorial, we will learn how to create our own CAPTCHAs and then integrate them with the contact form we created in the tutorial.

Creating the CAPTCHA

We will use the PHP GD library to create our CAPTCHA. You can learn more about writing text and drawing shapes with GD in one of my earlier tutorials. We will also have to write a little bit of code to create our random string to be written on the image that's created. Yet another tutorial, titled Generating Random Alphanumeric Strings in PHP, can help us in this regard.

Generate a Random String

All the code from this section will go in the captcha.php file. Let's begin by writing the function to create the random string.

<?php $permitted_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; function generate_string($input, $strength = 5) { $input_length = strlen($input); $random_string = ''; for($i = 0; $i < $strength; $i++) { $random_character = $input[mt_rand(0, $input_length - 1)]; $random_string .= $random_character; } return $random_string; } $string_length = 6; $captcha_string = generate_string($permitted_chars, $string_length); ?>

The $permitted_chars variable stores all the characters that we want to use to generate our CAPTCHA string. We are only using capital letters in the English alphabet to avoid any confusion that might arise due to letters or numbers that might look alike. You can use any set of characters that you like to increase or decrease the difficulty of the CAPTCHA.

Our function creates a five-letter string by default, but you can change that value by passing a different parameter to the generate_string() function.

Render the CAPTCHA Background

Once we have our random string, it's time to write the code to create the background of the CAPTCHA image. The image will be 200 x 50 pixels in size and will use five different colors for the background.

<?php $image = imagecreatetruecolor(200, 50); imageantialias($image, true); $colors = []; $red = rand(125, 175); $green = rand(125, 175); $blue = rand(125, 175); for($i = 0; $i < 5; $i++) { $colors[] = imagecolorallocate($image, $red - 20*$i, $green - 20*$i, $blue - 20*$i); } imagefill($image, 0, 0, $colors[0]); for($i = 0; $i < 10; $i++) { imagesetthickness($image, rand(2, 10)); $rect_color = $colors[rand(1, 4)]; imagerectangle($image, rand(-10, 190), rand(-10, 10), rand(-10, 190), rand(40, 60), $rect_color); } ?>

We begin with random values for the variables $red, $green, and $blue. These values determine the final color of the image background. After that, we run a for loop to create progressively darker shades of the original color. These colors are stored in an array. The lightest color is the first element of our $colors array, and the darkest color is the last element. The lightest color is used to fill the whole background of the image.

In the next step, we use a for loop to draw rectangles at random locations on our original image. The thickness of the rectangles varies between 2 and 10, while the color is chosen randomly from the last four values of our $colors array.

Drawing all these rectangles adds more colors to the background, making it a little harder to distinguish the foreground of the CAPTCHA string from the background of the image.

Your CAPTCHA background should now look similar to the following image.

Render the CAPTCHA String

For the final step, we just have to draw the CAPTCHA string on our background. The color, y-coordinate, and rotation of individual letters is determined randomly to make the CAPTCHA string harder to read.

<?php $black = imagecolorallocate($image, 0, 0, 0); $white = imagecolorallocate($image, 255, 255, 255); $textcolors = [$black, $white]; $fonts = [dirname(__FILE__).'\fonts\Acme.ttf', dirname(__FILE__).'\fonts\Ubuntu.ttf', dirname(__FILE__).'\fonts\Merriweather.ttf', dirname(__FILE__).'\fonts\PlayfairDisplay.ttf']; $string_length = 6; $captcha_string = generate_string($permitted_chars, $string_length); for($i = 0; $i < $string_length; $i++) { $letter_space = 170/$string_length; $initial = 15; imagettftext($image, 20, rand(-15, 15), $initial + $i*$letter_space, rand(20, 40), $textcolors[rand(0, 1)], $fonts[array_rand($fonts)], $captcha_string[$i]); } header('Content-type: image/png'); imagepng($image); imagedestroy($image); ?>

As you can see, I'm using some fonts I downloaded from Google to get variation in the characters. There is a padding of 15 pixels on both sides of the image. The leftover space—170 pixels—is divided equally among all the CAPTCHA letters.

After rendering the text string above the background, your result should look similar to the image below. The characters will be different, but they should be slightly rotated and a mix of black and white.

Adding the CAPTCHA to Our Contact Form

Now that we have created our CAPTCHA, it's time to add it to our contact form. We will use the contact form from my previous tutorial on how to create a PHP contact form and add the CAPTCHA just above the Send Message button.

We will be using sessions to store the CAPTCHA text and then validating the text entered by website visitors. Here is the complete code of our captcha.php file:

<?php session_start(); $permitted_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; function generate_string($input, $strength = 10) { $input_length = strlen($input); $random_string = ''; for($i = 0; $i < $strength; $i++) { $random_character = $input[mt_rand(0, $input_length - 1)]; $random_string .= $random_character; } return $random_string; } $image = imagecreatetruecolor(200, 50); imageantialias($image, true); $colors = []; $red = rand(125, 175); $green = rand(125, 175); $blue = rand(125, 175); for($i = 0; $i < 5; $i++) { $colors[] = imagecolorallocate($image, $red - 20*$i, $green - 20*$i, $blue - 20*$i); } imagefill($image, 0, 0, $colors[0]); for($i = 0; $i < 10; $i++) { imagesetthickness($image, rand(2, 10)); $line_color = $colors[rand(1, 4)]; imagerectangle($image, rand(-10, 190), rand(-10, 10), rand(-10, 190), rand(40, 60), $line_color); } $black = imagecolorallocate($image, 0, 0, 0); $white = imagecolorallocate($image, 255, 255, 255); $textcolors = [$black, $white]; $fonts = [dirname(__FILE__).'\fonts\Acme.ttf', dirname(__FILE__).'\fonts\Ubuntu.ttf', dirname(__FILE__).'\fonts\Merriweather.ttf', dirname(__FILE__).'\fonts\PlayfairDisplay.ttf']; $string_length = 6; $captcha_string = generate_string($permitted_chars, $string_length); $_SESSION['captcha_text'] = $captcha_string; for($i = 0; $i < $string_length; $i++) { $letter_space = 170/$string_length; $initial = 15; imagettftext($image, 24, rand(-15, 15), $initial + $i*$letter_space, rand(25, 45), $textcolors[rand(0, 1)], $fonts[array_rand($fonts)], $captcha_string[$i]); } header('Content-type: image/png'); imagepng($image); imagedestroy($image); ?>

The fonts that you want to use will go into the fonts directory. Now, you simply have to add the following HTML code above the Send Message button from our previous tutorial on creating a contact form in HTML and PHP.

<div class="elem-group"> <label for="captcha">Please Enter the Captcha Text</label> <img src="captcha.php" alt="CAPTCHA" class="captcha-image"><i class="fas fa-redo refresh-captcha"></i> <br> <input type="text" id="captcha" name="captcha_challenge" pattern="[A-Z]{6}"> </div>

Sometimes, the CAPTCHA text will be hard to read even for humans. In these situations, we want them to be able to ask for a new CAPTCHA in a user-friendly manner. The redo icon above helps us do exactly that. All you have to do is add the JavaScript below on the same page as the HTML for the contact form.

var refreshButton = document.querySelector(".refresh-captcha"); refreshButton.onclick = function() { document.querySelector(".captcha-image").src = 'captcha.php?' + Date.now(); }

After integrating the CAPTCHA in the form and adding a refresh button, you should get a form that looks like the image below.

The final step in our integration of the CAPTCHA we created with the contact form involves checking the CAPTCHA value input by users when filling out the form and matching it with the value stored in the session. Update the contact.php file from the previous tutorial to have the following code.

<?php session_start(); if($_POST) { $visitor_name = ""; $visitor_email = ""; $email_title = ""; $concerned_department = ""; $visitor_message = ""; if(isset($_POST['captcha_challenge']) && $_POST['captcha_challenge'] == $_SESSION['captcha_text']) { if(isset($_POST['visitor_name'])) { $visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING); } if(isset($_POST['visitor_email'])) { $visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']); $visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL); } if(isset($_POST['email_title'])) { $email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING); } if(isset($_POST['concerned_department'])) { $concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING); } if(isset($_POST['visitor_message'])) { $visitor_message = htmlspecialchars($_POST['visitor_message']); } if($concerned_department == "billing") { $recipient = "billing@domain.com"; } else if($concerned_department == "marketing") { $recipient = "marketing@domain.com"; } else if($concerned_department == "technical support") { $recipient = "tech.support@domain.com"; } else { $recipient = "contact@domain.com"; } $headers = 'MIME-Version: 1.0' . "\r\n" .'Content-type: text/html; charset=utf-8' . "\r\n" .'From: ' . $visitor_email . "\r\n"; if(mail($recipient, $email_title, $visitor_message, $headers)) { echo '<p>Thank you for contacting us. You will get a reply within 24 hours.</p>'; } else { echo '<p>We are sorry but the email did not go through.</p>'; } } else { echo '<p>You entered an incorrect Captcha.</p>'; } } else { echo '<p>Something went wrong</p>'; } ?>

We updated this file to first check if the CAPTCHA value stored in the session is the same as the value input by the user. If they are different, we simply tell the visitors that they entered an incorrect CAPTCHA. You can handle the situation differently based on what your project needs.

Final Thoughts

In this tutorial, we created our own CAPTCHA in PHP from scratch and integrated it with a PHP contact form we built in one of our earlier tutorials. We also made the CAPTCHA more user-friendly by adding a refresh button so that users get a new string with a new background in case the previous one was unreadable.

You can also use the logic from this tutorial to create a CAPTCHA that relies on solving basic mathematical equations like addition and subtraction. 

If you want to add a CAPTCHA to your website, you should check out some of the form and CAPTCHA plugins available from CodeCanyon. Some of these have CAPTCHA and many other features like a file uploader built in. 

If you have any questions or suggestions, feel free to let me know in the comments. You should also take a look at this list of best PHP contact forms.

Categories: Web Design

Object-Oriented PHP With Classes and Objects

Mon, 12/03/2018 - 20:06

In this article, we're going to explore the basics of object-oriented programming in PHP. We'll start with an introduction to classes and objects, and we'll discuss a couple of advanced concepts like inheritance and polymorphism in the latter half of this article.

What Is Object-Oriented Programming (OOP)?

Object-oriented programming, commonly referred to as OOP, is an approach which helps you to develop complex applications in a way that's easily maintainable and scalable over the long term. In the world of OOP, real-world entities such as Person, Car, or Animal are treated as objects. In object-oriented programming, you interact with your application by using objects. This contrasts with procedural programming, where you primarily interact with functions and global variables.

In OOP, there's a concept of "class", which is used to model or map a real-world entity to a template of data (properties) and functionality (methods). An "object" is an instance of a class, and you can create multiple instances of the same class. For example, there is a single Person class, but many person objects can be instances of this class—dan, zainab, hector, etc. 

The class defines properties. For example, for the Person class, we might have name, age, and phoneNumber. Then each person object will have its own values for those properties. 

You can also define methods in the class that allow you to manipulate the values of object properties and perform operations on objects. As an example, you could define a save method which saves the object information to a database.

What Is a PHP Class?

A class is a template which represents a real-world entity, and it defines properties and methods of the entity. In this section, we’ll discuss the basic anatomy of a typical PHP class.

The best way to understand new concepts is with an example. So let's have a look at the Employee class in the following snippet, which represents the employee entity.

<?php class Employee { private $first_name; private $last_name; private $age; public function __construct($first_name, $last_name, $age) { $this->first_name = $first_name; $this->last_name = $last_name; $this->age = $age; } public function getFirstName() { return $this->first_name; } public function getLastName() { return $this->last_name; } public function getAge() { return $this->age; } } ?>

The class Employee statement in the first line defines the Employee class. Then, we go on to declare the properties, the constructor, and the other class methods.

Class Properties in PHP

You could think of class properties as variables that are used to hold information about the object. In the above example, we’ve defined three propertiesfirst_name, last_name, and age. In most cases, class properties are accessed via instantiated objects.

These properties are private, which means they can only be accessed from within the class. This is the safest access level for properties. We’ll discuss the different access levels for class properties and methods later in this article.

Constructors for PHP Classes

A constructor is a special class method which is called automatically when you instantiate an object. We’ll see how to instantiate objects in the next couple of sections, but for now you just have to know that a constructor is used to initialize object properties when the object is being created.

You can define a constructor by defining the __construct method.

Methods for PHP Classes

We can think of class methods as functions that perform specific actions associated with objects. In most cases, they are used to access and manipulate object properties and perform related operations.

In the above example, we’ve defined the getLastName method, which returns the last name associated with the object. 

So that’s a brief introduction to the class structure in PHP. In the next section, we’ll see how to instantiate objects of the Employee class.

What Is an Object in PHP?

In the previous section, we discussed the basic structure of a class in PHP. Now, when you want to use a class, you need to instantiate it, and the end result is an object. So we could think of a class as a blueprint, and an object is an actual thing that you can work with.

In the context of the Employee class which we've just created in the previous section, let's see how to instantiate an object of that class.

<?php $objEmployee = new Employee('Bob', 'Smith', 30); echo $objEmployee->getFirstName(); // print 'Bob' echo $objEmployee->getLastName(); // prints 'Smith' echo $objEmployee->getAge(); // prints '30' ?>

You need to use the new keyword when you want to instantiate an object of any class along with its class name, and you'll get back a new object instance of that class.

If a class has defined the __construct method and it requires arguments, you need to pass those arguments when you instantiate an object. In our case, the Employee class constructor requires three arguments, and thus we've passed these when we created the $objEmployee object. As we discussed earlier, the __construct method is called automatically when the object is instantiated.

Next, we've called class methods on the $objEmployee object to print the information which was initialized during object creation. Of course, you can create multiple objects of the same class, as shown in the following snippet.

<?php $objEmployeeOne = new Employee('Bob', 'Smith', 30); echo $objEmployeeOne->getFirstName(); // prints 'Bob' echo $objEmployeeOne->getLastName(); // prints 'Smith' echo $objEmployeeOne->getAge(); // prints '30' $objEmployeeTwo = new Employee('John', 'Smith', 34); echo $objEmployeeTwo->getFirstName(); // prints 'John' echo $objEmployeeTwo->getLastName(); // prints 'Smith' echo $objEmployeeTwo->getAge(); // prints '34' ?>

The following image is a graphical representation of the Employee class and some of its instances.

Simply put, a class is a blueprint which you can use to create structured objects.

Encapsulation

In the previous section, we discussed how to instantiate objects of the Employee class. It's interesting to note that the $objEmployee object itself wraps together properties and methods of the class. In other words, it hides those details from the rest of the program. In the world of OOP, this is called data encapsulation.

Encapsulation is an important aspect of OOP that allows you to restrict access to certain properties or methods of the object. And that brings us to another topic for discussionaccess levels.

Access Levels

When you define a property or a method in a class, you can declare it to have one of these three access levelspublic, private, or protected.

Public Access

When you declare a property or a method as public, it can be accessed from anywhere outside the class. The value of a public property can be modified from anywhere in your code.

Let's look at an example to understand the public access level.

<?php class Person { public $name; public function getName() { return $this->name; } } $person = new Person(); $person->name = 'Bob Smith'; echo $person->getName(); // prints 'Bob Smith' ?>

As you can see in the above example, we've declared the name property to be public. Hence, you can set it from anywhere outside the class, as we've done here.

Private Access

When you declare a property or a method as private, it can only be accessed from within the class. This means that you need to define getter and setter methods to get and set the value of that property.

Again, let's revise the previous example to understand the private access level.

<?php class Person { private $name; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } } $person = new Person(); $person->name = 'Bob Smith'; // Throws an error $person->setName('Bob Smith'); echo $person->getName(); // prints 'Bob Smith' ?>

If you try accessing a private property from outside the class, it'll throw the fatal error Cannot access private property Person::$name. Thus, you need to set the value of the private property using the setter method, as we did using the setName method.

There are good reasons why you might want to make a property private. For example, perhaps some action should be taken (updating a database, say, or re-rendering a template) if that property changes. In that case, you can define a setter method and handle any special logic when the property is changed.

Protected Access

Finally, when you declare a property or a method as protected, it can be accessed by the same class that has defined it and classes that inherit the class in question. We'll discuss inheritance in the very next section, so we'll get back to the protected access level a bit later.

Inheritance

Inheritance is an important aspect of the object-oriented programming paradigm which allows you to inherit properties and methods of other classes by extending them. The class which is being inherited is called the parent class, and the class which inherits the other class is called the child class. When you instantiate an object of the child class, it inherits the properties and methods of the parent class as well.

Let's have a look at the following screenshot to understand the concept of inheritance.

In the above example, the Person class is the parent class, and the Employee class extends or inherits the Person class and so is called a child class.

Let's try to go through a real-world example to understand how it works.

<?php class Person { protected $name; protected $age; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } private function callToPrivateNameAndAge() { return "{$this->name} is {$this->age} years old."; } protected function callToProtectedNameAndAge() { return "{$this->name} is {$this->age} years old."; } } class Employee extends Person { private $designation; private $salary; public function getAge() { return $this->age; } public function setAge($age) { $this->age = $age; } public function getDesignation() { return $this->designation; } public function setDesignation($designation) { $this->designation = $designation; } public function getSalary() { return $this->salary; } public function setSalary($salary) { $this->salary = $salary; } public function getNameAndAge() { return $this->callToProtectedNameAndAge(); } } $employee = new Employee(); $employee->setName('Bob Smith'); $employee->setAge(30); $employee->setDesignation('Software Engineer'); $employee->setSalary('30K'); echo $employee->getName(); // prints 'Bob Smith' echo $employee->getAge(); // prints '30' echo $employee->getDesignation(); // prints 'Software Engineer' echo $employee->getSalary(); // prints '30K' echo $employee->getNameAndAge(); // prints 'Bob Smith is 30 years old.' echo $employee->callToPrivateNameAndAge(); // produces 'Fatal Error' ?>

The important thing to note here is that the Employee class has used the extends keyword to inherit the Person class. Now, the Employee class can access all properties and methods of the Person class that are declared as public or protected. (It can't access members that are declared as private.)

In the above example, the $employee object can access getName and setName methods that are defined in the Person class since they are declared as public.

Next, we've accessed the callToProtectedNameAndAge method using the getNameAndAge method defined in the Employee class, since it's declared as protected. Finally, the $employee object can't access the callToPrivateNameAndAge method of the Person class since it's declared as private.

On the other hand, you can use the $employee object to set the age property of the Person class, as we did in the setAge method which is defined in the Employee class, since the age property is declared as protected.

So that was a brief introduction to inheritance. It helps you to reduce code duplication, and thus encourages code reusability.

Polymorphism

Polymorphism is another important concept in the world of object-oriented programming which refers to the ability to process objects differently based on their data types.

For example, in the context of inheritance, if the child class wants to change the behavior of the parent class method, it can override that method. This is called method overriding. Let's quickly go through a real-world example to understand the concept of method overriding.

<?php class Message { public function formatMessage($message) { return printf("<i>%s</i>", $message); } } class BoldMessage extends Message { public function formatMessage($message) { return printf("<b>%s</b>", $message); } } $message = new Message(); $message->formatMessage('Hello World'); // prints '<i>Hello World</i>' $message = new BoldMessage(); $message->formatMessage('Hello World'); // prints '<b>Hello World</b>' ?>

As you can see, we've changed the behavior of the formatMessage method by overriding it in the BoldMessage class. The important thing is that a message is formatted differently based on the object type, whether it's an instance of the parent class or the child class.

(Some object-oriented languages also have a kind of method overloading that lets you define multiple class methods with the same name but a different number of arguments. This isn't directly supported in PHP, but there are a couple of workarounds to achieve similar functionality.)

Conclusion

Object-oriented programming is a vast subject, and we've only scratched the surface of its complexity. I do hope that this tutorial helped you get you started with the basics of OOP and that it motivates you to go on and learn more advanced OOP topics.

Object-oriented programming is an important aspect in application development, irrespective of the technology you're working with. Today, in the context of PHP, we discussed a couple of basic concepts of OOP, and we also took the opportunity to introduce a few real-world examples.

Feel free to post your queries using the feed below!

Categories: Web Design

Best Practices for ARIA Implementation

Sun, 12/02/2018 - 17:01

Today, to mark the International Day of Persons With Disabilities, we are highlighting accessibility here at Envato Tuts+.

ARIA is an important feature that web developers can use to help make their sites more accessible. In previous pieces, we talked about how you can implement ARIA, whether you’re doing so on an eCommerce site or in more niche places.

So far, the focus of this series has been on how to implement ARIA—for example, how to add a role to an element or how to code more accessible forms. With this piece, the focus is going to shift a bit towards other aspects of online accessibility, like why and when we should use ARIA. We’ll also cover some common questions asked on previous posts throughout the series.

Alright, let’s begin!

What Is ARIA?

At its base, ARIA is an extension to current web development languages (mainly HTML) that allows for enhanced accessibility to end users.

What exactly does that mean, though?

Extending HTML With ARIA

HTML has some shortcomings when it comes to how elements are defined and how elements can be related to one another.

In many cases, HTML elements (such as the <div> tag) are too broadly defined to be useful to someone navigating a site with a screen reader, or an element may have too many possible meanings to be interpreted (e.g. an image could also be used as a button). ARIA adds additional attributes to HTML elements to allow for definitions that can be layered on top of the already existing markup language, adding clarity as needed.

The second major benefit is the relation of elements. With HTML, every element exists as a child and/or a parent of another element. But this structure doesn't capture all semantic relationships. This can lead to scenarios like a controller and the element it controls not being clearly associated if they are placed in separate div containers. This becomes increasingly important in complex site structures or when altering the DOM using JavaScript.

Beyond those two benefits, there are a host of others that tend to get less attention, but provide excellent functionality nonetheless.

ARIA for Advanced Accessibility

Although much of the web is pushing towards easier-to-use UX, ARIA fills an important role for others who may not be able to simplify their structure. There are cases where a website might require tree controls, such as those commonly used by filesystems. By providing additional structure, ARIA makes these more advanced controls available to people who might not be able to access them otherwise—especially for users seeking to create a site with drag-and-drop capabilities.

Another key capability is that ARIA doesn’t just extend HTML—it can also be used to make other, less accessibility-friendly technologies available to more users. This is often the case for people using AJAX or DHTML for their web applications.

And really, those are just scratching the surface. If you’re interested in finding out more about the capabilities, attributes, and other useful parameters, take a look at the WAI-ARIA overview.

Why Should We Use ARIA?

As far as accessibility is concerned, ARIA has become one of the most widely adopted standards, with more than 25% of the top million websites using it to some extent.

The biggest boon of using WAI-ARIA is that it increases accessibility on your site. Users that rely on screen readers, have low vision, or use alternative interfaces for the web benefit greatly from the implementation—and in some cases, they may not be able to use a website to its full extent without it. For many, accessibility is seen as a core value of the web, and as developers, we should strive to provide it wherever possible.

Beyond the best practices aspect, there is also a business incentive to implement ARIA. With 2-3% of Americans having some form of low vision, there is a significant portion of most markets that would benefit from use of the standard. In addition, having an implementation in place now will be beneficial as adoption of ARIA increasingly grows among non-standard web interfaces and creeps into devices such as smart speakers.

Best Practices for ARIA Implementation

Until now, we’ve focused on the actual methods of implementation in this series. With the basics of how to add ARIA to your site in place now, let’s take a look at some key guidelines for putting together your own implementation.

Using a Light Touch Approach

A good implementation of ARIA doesn’t need additional attributes and roles at every opportunity.

When possible, using the least amount of additional code to convey the necessary information is ideal. As an example, the overuse of ARIA is similar to making your site’s homepage a full sitemap for a visual user. People using screen readers will be overwhelmed by the amount of notifications and additional markup on a page that overutilizes ARIA, achieving the opposite of what we were seeking.

Providing enough additional markup to make your important elements’ context clear is the goal, and anything beyond that is probably not necessary.

Avoiding Redundancy (Especially When Using HTML5)

Throughout the previous posts in this series, we talked about the role attribute quite a bit. We placed it in every place that we needed the user to be aware of. There’s an important exception to this, however, that we didn’t talk about before, and that’s the need to avoid redundancy.

Whenever an element that you want to add ARIA to already clearly defines what it is, then you can skip adding ARIA to it. Why is this? Because ARIA is meant to extend existing code to make it more readable, but in some cases, code is already clear, structured, and easy to understand.

This happens frequently for people using elements introduced in HTML5. For example, when using the <button> element, you no longer need to add in the attribute role="button", since the role is already explicitly defined by the HTML code.

Testing With a Screen Reader

Another key to creating a good ARIA implementation is to make sure that you are testing your site with a screen reader or two. You’re likely to be surprised at the details of how they function and how easy it is to make your website annoying to use by accident.

Many ARIA attributes can create notifications or alerts for the end user, and if you are utilizing an aria-live content area that changes every 10 seconds, it's possible that the implementation is making it more difficult to use your website.

Iterative Accessibility for the Web

When adding additional accessibility measures to your site, it's important to remember that it isn’t an all or nothing task. You don’t have to completely deck out your entire website in one attempt, and iterative additions are probably the best way to go.

Starting with major content areas and navigations and then spreading throughout the site slowly is a solid strategy, completing more as time goes on. Even if you schedule 15 or 30 minutes each month to add just a bit of accessibility to your site, it’s a step in the right direction.

Good UX Is Good Accessibility (And Vice Versa)

ARIA isn’t a cure-all for accessibility issues. It is crucial to place a heavy focus on good UX design, especially when it comes to text readability, as another tool in your accessibility toolkit.

If you’d like to delve deeper into the specifics of how UX and development (outside of ARIA) can be wielded to improve accessibility, take a look at the Web Content Accessibility Guidelines.

You can also take a look at our Complete Learning Guide to Web Accessibility.

Frequently Asked Questions About ARIA

This series on ARIA resonated with a lot of readers and sparked discussion in the community. Let’s keep it up! Increasing awareness and improving these tutorials is the best way to bring accessibility to the forefront.  

Here are some of the most common questions and commentary that popped up around the web:

What Browsers Support WAI-ARIA?

A bunch! Most modern browsers support the features of ARIA to some extent, though this slightly changes from browser to browser. If you want to see specifics for each browser, you can use a tool like Can I Use?

Can ARIA Be Used With WordPress?

Yep! A few WordPress themes already have ARIA integrated, but you can add it to any theme that you can edit the source code for. In addition, you can also use ARIA with almost any Content Management System!

What Happens If ARIA Isn’t Supported?

Since ARIA doesn’t affect rendering, nothing! In most cases, if a device doesn’t support ARIA, it’ll just be ignored entirely.

Make the Web a Better Place!

Putting all of the articles from this series together, I hope you now have all of the tools needed to improve the accessibility of your site!

If you have any questions, feedback, or have a correction for something I’ve said, please let me know in the comments!

Categories: Web Design

Accessible Apps: Barriers to Access and Getting Started With Accessibility

Sun, 12/02/2018 - 16:30

Today, we are highlighting accessibility—something we strive to think about every day here at Envato Tuts+. December 3 is International Day of Persons With Disabilities. Created by the United Nations in 1992, this day seeks to promote the rights and well-being of persons with disabilities in all spheres of society. More than one billion people worldwide live with some form of disability.

In the context of web and app development, the goal of accessibility is that your tool works for all people, regardless of the hardware or software they are using, and wherever they fall on the spectrum of hearing, movement, visual, and cognitive ability. With rapid changes in digital and assistive technology, meeting this goal requires thought, testing, and an overall understanding of the way online tools are used by different people with diverse needs.


There are tools here at Envato Tuts+ and across the web that can help you learn how to design and code for accessibility, and I will link to some in this article. But in this post, I would like to look at the role of developers in web accessibility and talk about why the best time to think about accessibility is at the beginning of a project. I'll also introduce some emerging issues around developing for accessibility, and raise considerations around barriers to access and advocate for the importance of engaging with users at different stages of the development process.

Thinking About Barriers to Access

The UN’s Convention on the Rights of Persons with Disabilities points out that the existence of barriers is a central feature of disability—that disability is an evolving relationship between people with impairments and the social and environment barriers with which they interact. Barriers are in themselves disabling, and exclusion is a structural problem that lives in our systems, rather than in the bodies of those with impairments. Because of this, removing barriers is a prerequisite to social inclusion for all people.

Let's think a bit about accommodations and barriers to access.

Last week, a friend pointed out that light bulbs are an assistive device for people who rely on their vision to get around. Using light bulbs in a building is a way to mitigate this barrier, since sighted people need light to navigate the world, but people without sight do not need this accommodation, as they navigate using other strategies. What we consider a “normal” accommodation is socially conditioned, rather than an objective truth.

I bring up this example to disrupt the idea of “normal” and move away from thinking of accessible design as a special accommodation. If we prioritize making our technology barrier-free, rather than thinking about accessibility as an exception or afterthought, we can shift the concept of “normal” to accommodate all people and exclude none.

The strength of web technology is that, by its nature, it removes barriers that exist in the physical world. When building web and mobile app technology, it is vital that we not add barriers back in to the technology through the way we design our tools. In order to do this, we have to understand how different people use our tools and what their needs are. And just like when considering whether to build a ramp or a set of stairs, the best time to think about this is before we start building.

Accessibility: Getting Started

When it comes to building accessible web tools, there are two main considerations: take advantage of existing accessibility infrastructure, and stay out of the way of assistive devices and other accessibility strategies.

Using alt text for all non-text elements (images, graphs, charts, etc.) is an example of how you can take advantage of existing infrastructure. Screen readers rely on alt text to parse web content for visitors with visual impairments. This is not a complicated fix—alt text is simply good design. By designing for accessibility, you will improve the functionality of your website. In this case, search engines rely on alt text to better “read” websites. According to the W3, case studies show that accessible websites have better search results and increased audience reach.

Ensuring that keyboard input works with your tool is an example of staying out of the way of users’ accessibility strategies. Using a mouse requires a degree of fine motor control that many people do not have, so they rely on keyboard input to navigate websites and apps. If your web tool can be navigated with keyboard input, it also allows assistive technologies that mimic the keyboard, such as speech input, to function properly. If you build a tool that cannot be navigated with keyboard input, you are unnecessarily creating an inaccessible environment for users.

Knowing how different people interact with your web tool gives you the ability to make choices that support their accessibility strategies. It is so much better to do this at the beginning of a project than try to address accessibility as an afterthought. An illustrative example: UC Berkeley ran into trouble when they made thousands of uncaptioned videos—inaccessible to people with hearing impairments—available online. The university was legally required to caption the content, but did not want to pay for the expensive project, and eventually cancelled the project outright.

By making websites more accessible, you make your web tools work better, more of the time, for more people. The power you have as a developer allows you to address accessibility issues at the earliest stages, when it is the easiest and least expensive time to do so.

Tools and Guides on Accessibility

Here at Envato Tuts+, we have a variety of information on how to build better, more accessible, web tools. Here are a few to get you started.

ARIA (the Accessible Rich Internet Applications Suite) is a tool to make web content and apps more accessible, especially for people who use screen readers or cannot use a mouse. The main purpose of ARIA is to allow for advanced semantic structure within HTML as a counterpart to HTML’s syntax-heavy nature. In other words, HTML tells the browser where things go, and ARIA tells it how they interact. In this series, you'll learn how to use ARIA to make your web apps more accessible.

In this post, you'll learn some tips to make your web page more keyboard accessible, using only basic HTML and CSS.

It's important to make sure your checkboxes and radio buttons remain accessible to assistive technology (AT) and keyboard users. In this post, you'll learn how to make sure your custom checkboxes and radio buttons are accessible.

Complete Learning Guide to Web Accessibility

This is a collection of tutorials, articles, courses, and quick tips to walk you through the basics of accessibility.

I encourage you to also check out some source guides on accessibility from the W3. The W3 article on accessibility principles is a good place to start. They also have an article about strategies internet users can employ to make the web more accessible—this will get you started thinking about how different people have different accessibility needs and how you can code to support accessibility for everyone. And this article goes over ways to optimize your computer for more accessible web browsing, which will give you an idea of some of the strategies people employ to make the internet more accessible for themselves.

User Testing Is Everything

You’ve thought about accessibility. You are committed to removing barriers to access in your web and mobile apps. You’ve built a tool with up-to-date accessibility guidelines in mind. Is your app accessible?

There are guides on Tools and Tips for Testing for Accessibility, and that is an important part of the design process. Reading the guide and testing your web tool is a great idea. But go further: the gold standard in designing for accessibility is user testing. Involve users early in your project and throughout the development process.

Some accessibility requirements are easy to meet, and some are more challenging. Understanding how different people use your tools will give you so much insight into how to build for accessibility. Everyone has different needs, different browsers, different assistive devices. No guide or checklist is going to be able to fully capture the breadth of experience of the people using your tool.

Like learning that users are receiving error reports or a 404 page, be grateful if and when you receive feedback that your tool is not currently meeting a user’s accessibility needs. Solicit this kind of feedback. Keep an open dialog with users and find solutions to the issues they bring to your attention. 

Anything you build will evolve—nothing is static in web and mobile technology. The real-life experience of your users is the most valuable input you can receive, so if you hear something is not working, say thank you. And then find a way to make it work.

Conclusion

Thank you for spending some time with me on this International Day of Persons With Disabilities. My intention with this article is to support the dialog around web and mobile accessibility and to give you a starting point for your own thoughts, research, and testing. Whether you are just getting started with programming or are an experienced programmer, it is so vital that you are prioritizing accessibility in your development projects, so that your tools can work well for each person who uses them.

Categories: Web Design

Dramatically Speed Up Your React Front-End App Using Lazy Loading

Thu, 11/15/2018 - 05:00

A constant challenge faced by front-end developers is the performance of our applications. How can we deliver a robust and full-featured application to our users without forcing them to wait an eternity for the page to load? The techniques used to speed up a website are so numerous that it can often be confusing to decide where to focus our energy when optimising for performance and speed.

Thankfully, the solution isn't as complicated as it sometimes might seem. In this post, I'll break down one of the most effective techniques used by large web apps to speed up their user experience. I'll go over a package to facilitate this and ensure that we can deliver our app to users faster without them noticing that anything has changed.

What Does It Mean for a Website to Be Fast?

The question of web performance is as deep as it is broad. For the sake of this post, I'm going to try and define performance in the simplest terms: send as little as you can as fast as you can. Of course, this might be an oversimplification of the problem, but practically speaking, we can achieve dramatic speed improvements by simply sending less data for the user to download and sending that data fast.

For the purpose of this post, I'm going to focus on the first part of this definition—sending the least possible amount of information to the user's browser. 

Invariably, the biggest offenders when it comes to slowing down our applications are images and JavaScript. In this post, I'm going to show you how to deal with the problem of large application bundles and speed up our website in the process.

React Loadable

React Loadable is a package that allows us to lazy load our JavaScript only when it's required by the application. Of course, not all websites use React, but for the sake of brevity I'm going to focus on implementing React Loadable in a server-side rendered app built with Webpack. The final result will be multiple JavaScript files delivered to the user's browser automatically when that code is needed.

Using our definition from before, this simply means we send less to the user up front so that data can be downloaded faster and our user will experience a more performant site.

1. Add React Loadable to Your Component

I'll take an example React component, MyComponent. I'll assume this component is made up of two files, MyComponent/MyComponent.jsx and MyComponent/index.js.

In these two files, I define the React component exactly as I normally would in MyComponent.jsx. In index.js, I import the React component and re-export it—this time wrapped in the Loadable function. Using the ECMAScript import feature, I can indicate to Webpack that I expect this file to be dynamically loaded. This pattern allows me to easily lazy load any component I've already written. It also allows me to separate the logic between lazy loading and rendering. That might sound complicated, but here's what this would look like in practice:

// MyComponent/MyComponent.jsx export default () => ( <div> This component will be lazy-loaded! </div> )// MyComponent/index.js import Loadable from 'react-loadable' export default Loadable({ // The import below tells webpack to // separate this code into another bundle loader: import('./MyComponent') })

I can then import my component exactly as I normally would:

// anotherComponent/index.js import MyComponent from './MyComponent' export default () => <MyComponent />

I've now introduced React Loadable into MyComponent. I can add more logic to this component later if I choose—this might include introducing a loading state or an error handler to the component. Thanks to Webpack, when we run our build, I'll now be provided with two separate JavaScript bundles: app.min.js is our regular application bundle, and myComponent.min.js contains the code we've just written. I'll discuss how to deliver these bundles to the browser a little later.

2. Simplify the Setup With Babel

Ordinarily, I'd have to include two extra options when passing an object to the Loadable function, modules and webpack. These help Webpack identify which modules we should be including. Thankfully, we can obviate the need to include these two options with every component by using the react-loadable/babel plugin. This automatically includes these options for us:

// input file import Loadable from 'react-loadable' export default Loadable({ loader: () => import('./MyComponent') })// output file import Loadable from 'react-loadable' import path from 'path' export default Loadable({ loader: () => import('./MyComponent'), webpack: () => [require.resolveWeak('./MyComponent')], modules: [path.join(__dirname, './MyComponent')] })

I can include this plugin by adding it to my list of plugins in my .babelrc file, like so:

{ "plugins": ["react-loadable/babel"] }

I'm now one step closer to lazy loading our component. However, in my case, I'm dealing with server-side rendering. Currently, the server will not be able to render our lazy-loaded components.

3. Rendering Components on the Server

In my server application, I have a standard configuration that looks something like this:

// server/index.js app.get('/', (req, res) => { const markup = ReactDOMServer.renderToString( <MyApp/> ) res.send(` <html> <body> <div id="root">${markup}</div> <script src="/build/app.min.js"></script> </body> </html> `) }) app.listen(8080, () => { console.log('Running...') })

The first step is going to be to instruct React Loadable that I want all modules to be preloaded. This allows me to decide which ones should be loaded immediately on the client. I do this by modifying my server/index.js file like so:

// server/index.js Loadable.preloadAll().then(() => { app.listen(8080, () => { console.log('Running...') }) })

The next step is going to be to push all components I want to render to an array so we can later determine which components require immediate loading. This is so the HTML can be returned with the correct JavaScript bundles included via script tags (more on this later). For now, I'm going modify my server file like so:

// server/index.js import Loadable from 'react-loadable' app.get('/', (req, res) => { const modules = [] const markup = ReactDOMServer.renderToString( <Loadable.Capture report={moduleName => modules.push(moduleName)}> <MyApp/> </Loadable> ) res.send(` <html> <body> <div id="root">${markup}</div> <script src="/build/app.min.js"></script> </body> </html> `) }) Loadable.preloadAll().then(() => { app.listen(8080, () => { console.log('Running...') }) })

Every time a component is used that requires React Loadable, it will be added to the modules array. This is an automatic process done by React Loadable, so this is all that's required on our part for this process.

Now we have a list of modules that we know will need to be rendered immediately. The problem we now face is mapping these modules to the bundles that Webpack has automatically produced for us.

4. Mapping Webpack Bundles to Modules

So now I've instructed Webpack to create myComponent.min.js, and I know that MyComponent is being used immediately, so I need to load this bundle in the initial HTML payload we deliver to the user. Thankfully, React Loadable provides a way for us to achieve this, as well. In my client Webpack configuration file, I need to include a new plugin:

// webpack.client.config.js import { ReactLoadablePlugin } from 'react-loadable/webpack' plugins: [ new ReactLoadablePlugin({ filename: './build/loadable-manifest.json' }) ]

The loadable-manifest.json file will provide me a mapping between modules and bundles so that I can use the modules array I set up earlier to load the bundles I know I'll need. In my case, this file might look something like this:

// build/loadable-manifest.json { "MyComponent": "/build/myComponent.min.js" }

This will also require a common Webpack manifest file to include the mapping between modules and files for internal Webpack purposes. I can do this by including another Webpack plugin:

plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity }) ]5. Including Bundles in Your HTML

The final step in loading our dynamic bundles on the server is to include these in the HTML we deliver to the user. For this step, I'm going to combine the output of steps 3 and 4. I can start by modifying the server file I created above:

// server/index.js import Loadable from 'react-loadable' import { getBundles } from 'react-loadable/webpack' import manifest from './build/loadable-manifest.json' app.get('/', (req, res) => { const modules = [] const markup = ReactDOMServer.renderToString( <Loadable.Capture report={moduleName => modules.push(moduleName)}> <MyApp/> </Loadable> ) const bundles = getBundles(manifest, modules) // My rendering logic below ... }) Loadable.preloadAll().then(() => { app.listen(8080, () => { console.log('Running...') }) })

In this, I've imported the manifest and asked React Loadable to create an array with module/bundle mappings. The only thing left for me to do is to render these bundles to an HTML string:

// server/index.js app.get('/', (req, res) => { // My App & modules logic res.send(` <html> <body> <div id="root">${markup}</div> <script src="/build/manifest.min.js"></script> ${bundles.map(({ file }) => `<script src="/build/${file}"></script>` }).join('\n')} <script src="/build/app.min.js"></script> </body> </html> `) }) Loadable.preloadAll().then(() => { app.listen(8080, () => { console.log('Running...') }) })6. Load the Server-Rendered Bundles on the Client

The final step to using the bundles that we've loaded on the server is to consume them on the client. Doing this is simple—I can just instruct React Loadable to preload any modules it's found to be immediately available:

// client/index.js import React from 'react' import { hydrate } from 'react-dom' import Loadable from 'react-loadable' import MyApplication from './MyApplication' Loadable.preloadReady().then(() => { hydrate( <MyApplication />, document.getElementById('root') ); });Conclusion

Following this process, I can split my application bundle into as many smaller bundles as I need. In this way, my app sends less to the user and only when they need it. I've reduced the amount of code that needs to be sent so that it can be sent faster. This can have significant performance gains for larger applications. It can also set smaller applications up for rapid growth should the need arise. 

Categories: Web Design

15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js

Tue, 10/30/2018 - 06:41

Are you building an app and looking for tools that can help you streamline your build? Take the effort out of your next front-end app build with one of these powerful admin templates.

Whether you prefer to work with React, Angular, or Vue.js, there are a range of templates available on ThemeForest that make it painless to create beautiful, interactive UIs. Built using cutting-edge technology, these templates offer flexibility and dependability for your app build. Create a stunning UI easily by selecting from modular components and clean layouts so that you can focus on the business logic of your app build.

React Admin Templates

React is a JavaScript library for building user interfaces that has taken the web development world by storm. React is known for its blazing-fast performance and has spawned an ecosystem of thousands of related modules on NPM, including many tooling options. 

These admin templates and dashboards are a great starting point for your next React app.

1. Isomorphic Admin Dashboard

Isomorphic is a React and Redux-powered single-page admin dashboard. It's based on a progressive web application pattern and is highly optimized for your next React app. With no need to install or configure tools like Webpack or Babel, you can get started building your app immediately. 

This template helps you write apps that behave consistently, run properly in different environments, and are easy to test. With Sass and CSS styling modules, multilingual support, a built-in Algolia search tool, Firestore CRUD, and easy-to-integrate code, you can use this template to build anything you want.

User justinr1234 says:

“Easily the most well-designed template using React out there, from both a code and design perspective. Integrating the code off the shelf was a breeze. If you have an existing app or are looking to roll a new one on the front end, this template successfully solves the problem for either use case. Excellent product!”2. Clean UI React Admin Template

Are you building a single-page app and interested in moving to React and Redux? Don’t start from scratch—build a scalable, highly polished admin app with this React, Redux, Bootstrap, and Ant Design template that works well on mobile, tablet, and desktop. 

Clean UI React is create-react-app based, so getting started is simple. Modular code allows you to add and remove components with ease. Developer friendly and highly customizable, this template includes 9 example apps, more than 50 pages, multiple layout options with easy-to-update Sass or CSS styling, and ample reusable React components.

User hermanaryadinata says:

“The quality is incredibly high and the flexibility is limitless! Highly recommended to buy!”3. Jumbo React Admin Template

Kick-start your app project with Jumbo React, a complete admin template. This product includes two React templates, one based on Google Material Design and the other on the stunning flat style. Each template comes with multiple design concepts and hundreds of UI components and widgets, as well as an internationalization feature that allows you to develop a multilingual app. 

Think of this template package as a starter kit to build your app. With it, you can develop a scalable React app rapidly and effectively and save yourself time and money in the process.

User Ace_Cooper says:

“Love the amount of components out-of-the-box. Right what I needed to jump start a new project.”4. Fuse Material Design Admin Template

Looking for a template to get your React project started? Fuse is a complete admin template that follows Google’s Material Design guidelines and will allow you to learn some of the advanced aspects of React while you build your app. 

This template uses Material UI as the primary UI library and Redux for state management. It comes with built-in page templates, routing, and authorization features, along with five example apps, more than 20 pages, and lots of reusable React components.

User DevX101 says:

“Very well organized template ready for building a real app. Not just visual templates, but includes authorization and modular design. Great starter kit.”Angular Admin Templates

Angular is more than just the next version of a popular front-end framework. Angular takes all the best parts of AngularJS and improves them. It's a powerful and feature-complete framework that you can use to build fast, professional web apps. 

Check out these templates that you can use to get your next Angular app off on the right foot with clean code and great design.

1. Fuse Material Design Admin Template

This best-selling template is a 3-in-1 bundle, with Angular 7+, Bootstrap 4, and 21 layered PSD designs. Fuse is based on Google Material Design and comes with AoT compiler support, as well as a complete NgRx example app. This template includes configurable layouts, a skeleton project, built-in apps such as calendar, e-commerce, mail, and chat, and more than 20 pages to get you started. 

Fuse supports all modern browsers (Chrome, Firefox, Safari, Edge) and comes with Bootstrap 4, HTML, and CSS versions, along with the Angular app.

User haseeb90 says:

“This is a great theme. Comes with pre-built apps that you just need to plug your logic and back end into. The code quality is great and stays up-to-date with the latest Angular versions.”2. Pages Admin Dashboard Template

Pages is the simplest and fastest way to build a web UI for your dashboard or app. This beautifully designed UI framework comes with hundreds of customizable features, which means that you can style every layout to look exactly the way you want it to. 

Pages is built with a clean, intuitive, and fully responsive design that works on all major browsers and devices. Featuring developer-friendly code, full Sass and RTL support, and five unique dashboard layouts, this Angular 5+ ready template boasts flawless design and a 5-star rating.

User roly14 says:

“Masterpiece. Simply stunning.”3. Clip-Two Bootstrap Admin Template For AngularJS

Clip-Two is an advanced, fully responsive admin template built with AngularJS. AngularJS, the original version of the popular Angular framework, lets you extend the HTML vocabulary. The resulting environment is expressive, readable, and quick to develop in. 

Using a Bootstrap UI, Clip-Two is mobile-friendly and comes with ready-to-customize themes with six different skins and infinite styles with SASS. This template includes features like four level sidebar menus, CSS3 page transitions, custom scrollbar for vertical scrollable content, dynamic pagination, and RTL functionality.

User hafizminhas says:

“This is one of the most outstanding Angular 1.x templates available in the market.”4. Apex Admin Template

Apex is a powerful and flexible admin template based on Angular 6+ and Bootstrap 4. The Angular CLI makes it easy to maintain and modify this app template. With easy-to-understand code and a handy starter kit, this template works right out of the box. Apex includes multiple solid and gradient menu color options and sizes, with an organized folder structure and more than 500 components and 50 widgets. 

This template is fully responsive, clean on every device and modern browser, and comes with AoT and lazy loading. Choose from a few pre-made layout options and customize with ready-to-use elements and popular UI components.

User jklayh says:

“These guys really know how to integrate everything well into one package, and the UI design is amazing. This is highly recommended.”5. Stack Admin Template and Starter Kit

Stack Admin is a Bootstrap 4 modern admin template with unlimited possibilities. This product includes eight pre-built templates with an organized folder structure, clean and commented code, and more than 1,500 pages and 1,000 components. Stack Admin provides RTL support, searchable navigation, unique menu layouts, and advanced cards. 

With three niche dashboards, Stack Admin can be used for any type of web app: project management, e-commerce back ends, analytics, or any custom admin panels. This template looks great on all devices, and it comes with a kit to help developers get started quickly.

User sietzekeuning says:

“Beautifully designed and has loads of very useful components. An absolute tip for anybody looking for a very well designed CMS!”6. Fury Material Design Admin Template

Clean, unique, and blazing fast, Fury is an admin template that offers you everything you need to get started with your next project. Built with Angular and Material Design, this template is the perfect framework for building large enterprise apps, and it allows for a modular component setup. 

This template is designed to be lightweight and easy to customize. Features include completely customizable dashboard widgets and Angular Flex-Layout, to provide a fast and flexible way to create your layouts.

User CreativelyMe says:

"The code quality is exceptional. It's clearly the work of a true craftsman. This template is truly a joy to work with, and continues to evolve over time. Excellent!!!"7. Able Pro 7.0 Responsive Template

Able Pro 7.0 is a fully responsive admin template that provides a flexible solution for your project development. Built with a Bootstrap 4 framework, this template has a Material look, with well structured and commented code. This retina-ready template comes with more than 150 pages and infinite design possibilities—use the Live Customizer feature to do one-click checks on color combinations and layout variations. 

With more than 100 external plugins included, advanced menu layout options, and ready-to-deploy dashboards and landing pages, Able Pro 7.0 will streamline your app development process to save you time and effort.

User macugi says:

“An amazing template. Very good design, good quality code and also very good customer support.”Vue.js Admin Templates

Vue.js is a front-end JavaScript framework that is easy to learn if you already know HTML and CSS. The versatility of Vue is great for small and large-scale web apps alike. On top of all this, it's blazing fast!

These Vue templates are sure to save you a lot of time and effort coding your next app.

1. Vuely—Material Design and Laravel Blade Admin Template

Vuely is a fully responsive admin template designed to give you a hassle-free development experience. Carefully crafted to look beautiful on mobile and tablet devices with pre-designed custom pages and integrated features like charts, graphs, and data tables, this template allows you to create your back-end panel with ease. More than 200 UI elements and 78 custom widgets simplify your development process. 

Vuely is translation ready with RTL support and comes with multiple color and theme options to give you the flexibility you need.

User alanoidster says:

“Good design quality, comprehensive components and features, great customer support!”2. VueJS Laravel Admin Template

Looking for a full featured admin template for your Vue.js project? Look no further. This Vue.js admin template is completely modular, so you can modify layouts, colors, and other features without disturbing the rest of the code. Simply customize it with the provided Sass variables. This template is well documented, with seven layout and multiple color scheme options. With all the components you need, this Vue.js template will get you started on your next dashboard build.

User JimOQuinn says:

“Wow, the look and feel of the theme has progressed substantially since the initial release. Great job! Love the no-jQuery framework as I find VueJS much easier to work with. Looking forward to the next release. Keep up the good work!”Multi-Framework Admin Templates

Finally, here are some templates that work with multiple frameworks.

1. Material Design Admin and Multipurpose Template

This Material Design admin template provides you high performance and clean and modern Vue, React and Angular versions. This super flexible template uses SCSS, Gulp, Webpack, NPM Modern Workflow, and Flexbox, and has all the components you need to create your front-end app project. With stunning layouts, over 500 components and lifetime updates and customer support, this is the most complete admin app available.

User themeuser55 says:

“This is an absolutely amazing theme. It is done with quality in mind, regularly updated, and you can tell the developer cares about his work and clients. I would suggest using this template if you are looking for a production worthy front end for a basis to any modern web application.”2. Primer—Angular and React Admin Template

Primer is a creative Material Design admin template, with ahead-of-time (AoT) compilation for a more performant user experience. Fully responsive and packaged with both Angular and React versions, this template has left-to-right and right-to-left (LTR/RTL) support and light and dark colour schemes. Well documented and easy to customize, with this app template you get everything you need to start working on your SaaS, CRM, CMS, or dashboard based project.

User cjackett says:

“This is a very well built template with great flexibility and lots of options. The author continues to update and improve the template, extending its functionality and incorporating new angular packages. Excellent work.”Conclusion

This is just a sample of the many app admin templates available on ThemeForest. There is a template for you, no matter what your style or specifications. These templates will make coding the front end of your app easier and help you deliver an app that provides a high-quality user experience. All this will save you time and effort, letting you focus on the real details of coding your project.

Categories: Web Design

New Course: Build an App With JavaScript and the MEAN Stack

Thu, 10/18/2018 - 03:39

You can make your web development work a whole lot easier by taking advantage of the MEAN stack (MongoDB, Express, Angular, and Node.js). Find out how in our comprehensive new course, Build an App From Scratch With JavaScript and the MEAN Stack

What You’ll Learn

Full-stack web development requires coding both a front-end for the browser and a back-end server. Using JavaScript for both parts of the app makes life a lot simpler for full-stack devs. With the MEAN technologies, you can code a cutting-edge web app in JavaScript, from the front-end all the way down to the database.

In this detailed 3.5-hour course, Derek Jensen will show you how to use the MEAN technologies to build full-stack web apps using only JavaScript (and its close cousin TypeScript). You'll start from absolute scratch, scaffolding an empty project, and build up a complete web app using the MEAN stack. 

You'll learn how to configure a MongoDB database, how to write a database abstraction layer, and how to create a REST API to make that data available to the front-end. On the client side, you'll learn how to structure an Angular app, how to create a service to connect with the back-end API, and how to implement each of the UI components that make a complete app.

Watch the Introduction Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 700,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Categories: Web Design

Hands-on With ARIA: Accessibility Recipes for Web Apps

Fri, 10/12/2018 - 05:31

In the confusing world of web applications, ARIA can help improve accessibility and ease of use for your creations. HTML isn't able to handle many types of relationship between elements on the page, but ARIA is ideal for almost any kind of setup you can come up with. Let’s take a look at what ARIA is, how it can apply to your web app, and some quick recipes you can use for your own sites.

Basics of ARIA

ARIA, also called WAI-ARIA, stands for the Web Accessibility Initiative–Accessible Rich Internet Applications. This initiative, updated by the W3C, aims to give developers a new set of schemas and attributes for making their creations more accessible. It specifically aims to cover the inherent gaps left by HTML. If you’re not familiar with what it does already, you should take a look at our primer on ARIA. You might also be interested in our pieces on ARIA for the Homepage and ARIA for eCommerce.

Briefly, though, ARIA has three main features that we'll be focusing on:

  1. Creating relationships outside of the parent-child association: HTML only allows for relationships between parent and child elements, but the associations we want to define aren't always nested within each other. ARIA lets us define element relationships outside of this constraint.
  2. Defining advanced controls and interactivity: HTML covers many basic UI elements, but there are many more advanced controls that are used around the web that are hard to define outside of their visual component. ARIA helps with that.
  3. Providing access to "live" area update attributes: the aria-live attribute gives screen readers and other devices a listener for when content on the page changes. This allows for easier communication of when on-screen content changes.
ARIA and Web Applications

Before, we looked at adding ARIA to the common elements of eCommerce pages and site homepages. With web apps, however, each one differs drastically from the last. Forms and functions shift between each app, and often even between versions of the same app. Because of this, we’ll treat our implementations here like recipes in a cookbook rather than a wholesale conversion of a page.

When it comes to web apps, a user’s intent is more difficult to discern in a generalized sense. With eCommerce, no matter which site you are on, it is likely that the visitors are looking to purchase a product or service. Web apps serve a variety of purposes, so instead, we’ll focus on creating nuanced controls that are accessible and user friendly.

Let’s get into some of these control types.

Controlling Live Updates With Buttons

The first control we’re going to look at is a displayed value updated by a button press. These types of controls are commonly seen where an element is displaying a quantity that may be adjusted by buttons labelled ‘+’ and ‘-’, but can take many forms, such as arrow buttons that let you cycle through predefined statuses.

A standard implementation can leave some gaps in understanding for the user. It is unclear what elements the buttons affect, how they affect them, and when the element’s value changes.

Below, we’ll use ARIA to create a connection between the buttons and the value display element using the aria-controls attribute. Then, we’ll make the use of the buttons clear by using aria-label and HTML <label>. Finally, we’ll utilize the aria alert role and the aria-live attribute to let our user know when the value is being updated.

Let’s take a look at what that code looks like:

<form action=""> <fieldset> <legend>Adjust Quantity</legend> <div> <label for="qty-element">Current Quantity</label> <input type="text" role="alert" aria-live="assertive" value="0" id="qty-element" /> <button type="button" aria-label='Add to Quantity' aria-controls="qty-element">+</button> <button type="button" aria-label='Subtract from Quantity' title="subtract 10" aria-controls="qty-element">=</button> </div> </fieldset> </form>ARIA Popups and Hover Tooltips

When outfitting a site with ARIA, it is common to use "progressive accessibility". The idea behind this term is that taking a site or web app from its basic form to fully accessible is a daunting task. To deal with this in a way that still makes forward movement, you can implement new features progressively and iteratively.

For a tooltip with a related popup or modal, this means that we can break the problem into two steps, rolling each out as we can. In this case, the tooltip we’re talking about is the common image of a small question mark that opens additional information when hovered over.

To let users know that the question mark image is actually a tooltip, we’ve defined it by using an appropriate role, like this:

<img src="question-mark.jpg" role='tooltip' />

There are a few issues with this implementation, though. Users may still not be aware that hovering over the tooltip initiates a popup with further information. Here’s how we can add that to our code:

<img src="question-mark.jpg" role='tooltip' aria-haspopup='true' aria-controls='tooltip-popup' /> <div id='tooltip-popup' aria-hidden='true'> Tooltip text </div>Accessible Input Tooltips

Instead of a hover-based tooltip, it’s also common for a web app to utilize forms where each input has its own associated tooltip.

Without additional ARIA markup, it can be difficult to tell which tooltips apply to which input for a user. Not having this relation in place can render your helper text useless in some cases.

To correct for this, we’ll wrap our tooltips within their own elements. Each of these can be nested near their related input, have their relations established with ARIA, and then can be triggered with JavaScript (or just CSS if you’re crafty).

Here’s how that could look:

<form action=""> <fieldset> <legend>User Login</legend> <div> <input type="text" id="user" aria-describedby="user-tip" /> <label for="user">Your Username</label> <div role="tooltip" id="user-tip">Tooltip about their username</div> </div> <div> <input type="password" id="password" aria-describedby="password-tip" /> <label for="password">Your Username</label> <div role="tooltip" id="password-tip">Tooltip about their password</div> </div> </fieldset> </form>Status Alerts

“Our service is currently down”, “Your account is suspended”, and related status alerts are commonly used among web apps, and display important information for users. Without ARIA, they can get buried within the information on a page and cause a variety of issues.

Utilizing the ARIA alert role and the aria-live attribute, we can make sure that our users are aware of any issues quickly once they arrive on a page.

We can set up this type of status alert like this:

<div id="system-status" role="alert" aria-live="assertive"> <p>The system is offline!</p> </div>Creating a Toolbar

Finally, let’s take a look at another common control element used within web apps: the toolbar. For our purposes, we’re going to be marking up a toolbar that works like this: our web app shows a large amount of data, oriented in a table. Above this table, our toolbar has several buttons that allow users to sort the table in various ways. These buttons include classic sort options such as A to Z and Z to A.

Relationally, these leave some problems concerning accessibility. First, it isn’t clear that those buttons affect the table—we’ll solve this using the aria-controls attribute. It also isn’t clear that the buttons are associated with each other, which may be a useful piece of information for our users. To define this, we’ll be using the toolbar role. Finally, a user doesn’t necessarily know which button was pressed last. To correct this, we’ll use the aria-pressed attribute.

When using the aria-pressed attribute, it's important to note that you’ll have to update these elements as the user interacts with them. This will likely require changing the attributes through JavaScript or jQuery.

Here’s what our toolbar code looks like:

<div role="toolbar" aria-label="Sorting Toolbs" aria-controls="data-table"> <button type="button" aria-pressed="false" aria-label='Sort Alphabetically, A to Z'>A to Z</button> <button type="button" aria-pressed="true" aria-label='Sort Alphabetically, Z to A'>Z to A</button> <button type="button" aria-pressed="false" aria-label='Sort Numerically'>Numerical</button> </div> <table id='data-table'> ... </table>Adding ARIA to Your Own Web Apps

With this handful of new control schemes and relations under your belt, you’re well on your way to making your own web app fully accessible! After you’ve added these new markups in, think about how you could apply these attributes to other parts of your user interface to maximize the usability of your creation.

Are there attributes, roles, or other features of ARIA that you’d like to know about? Or maybe you have some questions about your own implementations, or corrections for this article? Get in contact using the comment section below, or by tagging kylejspeaker on Twitter!

Categories: Web Design

10 Best WordPress Facebook Widgets

Thu, 10/04/2018 - 03:17

Facebook has over 2.23 billion active users worldwide who spend an average of 20 minutes per visit. That explains why, “on average, the Like and Share Buttons are viewed across almost 10 million websites daily” (via Zephoria).

Truth be told, Facebook cannot be ignored. Fortunately, CodeCanyon has some excellent plugins and widgets that will help you to integrate Facebook into your WordPress-powered website. From Facebook event calendars to a good-looking Facebook like box, here are the 10 best WordPress Facebook widgets worth your consideration:

1. Facebook Feed

The Facebook Feed WordPress widget is essentially four Facebook plugins in one.

With it, you can display your Facebook Posts Feed, Image Gallery, Video Gallery, and Events Calendar.

Features include:

  • fully responsive and ready for any screen size
  • includes Like and Share actions
  • supports Visual Composer
  • and more

Facebook Feed is a great way to get your Facebook content on your website.

2. Top Social Stories

You can add more than just your Facebook feed with Top Social Stories: it lets you easily track daily interactions on Facebook, Twitter, and more.

Features include:

  • display top stories based on most shares
  • export data to custom fields
  • works for custom post types
  • fully customizable
  • and more

Whether you need it solely for Facebook or you want to add other social media feeds into the mix, Top Social Stories is a great way to display social media posts.

3. Facebook Group Widget

This WordPress Facebook group widget is a great way to bridge the activity between your WordPress website and Facebook group.

The Facebook Group Widget displays the latest discussion from any public Facebook group.

This widget is:

  • CSS customizable
  • well documented
  • easy to use
  • responsive

Adjust the number of Facebook posts, set the word limit and a few other options, and you'll have the Facebook Group Widget easily added to your WordPress widget area.

4. Facebook Plugins, Comments & Dialogs for WordPress

The previous WordPress Facebook widget plugins have all targeted specific niche use-cases. Facebook Plugins, Comments & Dialogs for WordPress, however, is an all-in-one Facebook widget solution.

This WordPress Facebook plugin includes:

  • 11 total Facebook plugins integrated with one line of code
  • 8 customizable Facebook widgets
  • integrate Facebook comments
  • shortcode support
  • and much more

If you'd like the most feature-rich solution for integrating Facebook into your website, you need to consider the Facebook Plugins, Comments & Dialogs for WordPress plugin.

5. Facebook Recent Comments Widget

The Facebook Recent Comments Widget for WordPress brings the comment activity from your Facebook page and brings it to your WordPress widget area.

It's SEO friendly and super easy to use!

You can:

  • receive email notifications for Facebook comment box comments
  • manually or automatically approve comments to display
  • and customize the widget

Facebook Recent Comments Widget for WordPress is an easy way to display the latest Facebook comments on your WordPress-powered website.

6. Facebook Subscribe for WordPress

The Facebook Subscribe for WordPress plugin is the easiest way to add the Facebook Subscribe button to WordPress.

It also includes full template tag support along with easy-to-use shortcodes.

Additional features include:

  • built-in TinyMCE plugin to create subscribe buttons
  • supports button options, profile URL, layout, etc.
  • Facebook Locale API for other languages
  • and more

Facebook Subscribe for WordPress gives you everything you need to easily create Facebook Subscribe buttons without needing to know any code.

7. Social Stream for WordPress with Carousel

Social Stream for WordPress with Carousel is a viable option whether you're interested in only displaying Facebook content or content from multiple social media networks at one time.

With Social Stream, you can funnel all your social media streams to your WordPress-powered website in style.

There are several display options included with this social media carousel:

  • combine multiple social media feeds into one
  • 3 different styles and customizable colors
  • over 60 animation effects
  • responsive feed layout
  • and more

If you're interested in mixing in other social media streams along with your Facebook feed, Social Stream for WordPress with Carousel may be exactly what you're looking for.

8. Facebook Events Calendar

Display your Facebook events using a widget or shortcode with the Facebook Events Calendar.

This full-featured solution not only looks great, but has some great features as well.

Features include:

  • full and compact layouts
  • quick-view popups for each day
  • calendar and list views
  • and more

The Facebook Events Calendar is easy to use and one of the best ways to display your Facebook Page public events on your website. No need to maintain two calendars any more!

9. Jetpack by WordPress.com

If you're already using Jetpack by WordPress.com and only need a Facebook Like Box, using the free Jetpack plugin is a clear winner.

Open your Jetpack options, make sure the like box is enabled, and simply go into your widgets to place and configure it accordingly.

Set your options:

  • show faces, stream, or cover photo
  • Facebook page URL
  • title and height

And that's it. Jetpack by WordPress.com is simple, free, and may be all that you even need.

10. Facebook Social Plugins

Facebook does have a free plugin that's available in the WordPress Plugin Directory. However, while it has many options, it has not been updated in over two years and its ratings are dismal.

I suggest you avoid it.

However, Facebook does provide everything you need to create your own Facebook widget.

You can create:

  • embedded comments
  • share buttons
  • follow buttons
  • Like buttons
  • and more

Follow the online prompts and step-by-step instructions to configure your code. Dropping your snippet into the WordPress Text Widget may be all that's required for you to successfully set up your Facebook social plugin.

Build Your Own WordPress Facebook Widget

While most people will find the previously mentioned plugins and solutions useful, there are those who may find building their own WordPress Facebook widget the way to go.

There is extensive documentation from Facebook, and the Social Plugins provided by Facebook are a great place to begin building simple widgets.

And you'll find many WordPress How-To Tutorials from Envato that will help:

There are also Envato Tuts+ WordPress courses that can help you on your way to building your own WordPress Facebook widget.

Conclusion

There are many other Facebook WordPress plugins on CodeCanyon if you still haven't found exactly what you're looking for. Of course, if you still can't find what you're looking for, perhaps it's time to think about building your own and becoming an Envato author?

It's just a matter of comparing prices, options, and reading a few user reviews before finding the right Facebook widget. Facebook is a powerful social media platform that should not be overlooked. Integrating it into your website can make a big difference.

What kind of Facebook widget are you looking for?

Categories: Web Design

Hands-on With ARIA: Accessibility for eCommerce

Fri, 09/28/2018 - 17:09

Looking to make your site more accessible? Or maybe you want to make it easier to traverse your site overall using browsers and other interfaces? Using ARIA, you can do both. Let’s take a look at what ARIA is and how it can benefit an eCommerce site. We'll also go through some examples step by step.

What Is ARIA?

WAI-ARIA stands for the Web Accessibility Initiative–Accessible Rich Internet Applications. This initiative takes the form of a set of guidelines and attributes that are maintained by the W3C. Using these attributes, we can create relations between our site elements that can’t be expressed through HTML alone. The most important for our use here is that we can define element relations outside of the parent-child relationship, and more clearly connect UI elements for our users.

At this point, it might be a good idea to check out our original primer on ARIA to brush up on some of its foundations.

Adding ARIA to eCommerce

Previously, we talked about how to apply ARIA to a general website that resembled a common small business homepage. This time, we’re going to take a closer look at how ARIA can improve the user experience for large eCommerce sites.

We’re going to focus on four key areas of eCommerce that pose unique situations: product pages, category pages (or product aggregate pages), multi-level navigation, and faceted navigation. We’ll be using these two wireframes to guide us through the process:

A very basic product mockupExample of a Product Listing Page mockupPreparing for ARIA

In the case of most websites, adding ARIA is a fairly straightforward process. You define the pieces of your site, break them down into landmarks and elements, and add in the necessary code.

We’re going to follow a similar process with our eCommerce site, but we now have a new layer of intricacy. With the complexity that comes with eCommerce sites, ARIA can become a rabbit hole in many cases. While it is important to improve the accessibility of your site as much as possible, we unfortunately will often run into business constraints. Because of this, we’ll want to do a little more planning upfront, prioritizing each of our ARIA additions.

By doing this prioritization, we can ensure that the most important aspects of our site are improved first, making the user experience as good as we can in the time available.

Let’s kick it off by taking a look at some product pages.

ARIA for Product Pages

A staple page for any eCommerce site, these pages typically show a product, its available variations, and a way to add the item to a cart. Each of these interactive elements should be considered separately.

For our product page, let’s break it into pieces like this: our core product information, interactive elements that affect the product, our add to cart button, and an expanded content section.

If we needed to prioritize the implementation on this page, we would want to group it like so:

  1. Core product info, interactive elements, add to cart button
  2. Expanded product content

The main factor at play here is something we talked about in a previous article: ARIA helps to define an element’s intent. In the case of the expanded content, most of the HTML elements that are being used have elements with semantic meaning and intent that match. This means that while it is useful to put additional ARIA information if we can, it is likely less important than completing the other three areas.

Core Product Information

Let’s start off by adding ARIA to our core product information. This is pretty straightforward due to the simplicity of the elements being used here. The code looks like this:

<!-- Our code before any changes --> <div class='row-wrapper'> <div class='left-column'> <img src='bag-image.jpg' alt='brown bag' /> </div> <div class='right-column'> <h1>A Nice Bag</h1> <p>Bag Size:<br/>100x150mm</p> <select name='color-options'> <option value="brown">Brown</option> <option value="black">Black</option> </select> <input type="checkbox" value="Glossy"> <button>Add to cart</button> </div> </div>

For starters, we'll add a role to the main div, and a relationship between the image and the product title heading. 

<div class='row-wrapper' role='main'> <div class='left-column'> <img src='bag-image.jpg' alt='brown bag' aria-labelledby='product-title' /> </div> <div class='right-column'> <h1 id='product-title'>A Nice Bag</h1> ... </div> </div>Interactive Product Elements

This is where product pages can get a little tricky. Products on an eCommerce site can have quite a few different types of variations present. Beyond just the types available, the number of them that can be utilized simultaneously adds another layer of complexity. In our example, we have three elements that come into play: size, color, and quantity.

Let’s take a look at how you can mark that up. Here's the code for the ARIA-enhanced selection and checkbox elements:

<select name='color-options' aria-label='Color Selection Drop Down'> <option role='option' aria-selected='false' value="brown">Brown</option> <option role='option' aria-selected='false' value="black">Black</option> </select> <input type="checkbox" value="Glossy" role="checkbox" aria-checked="false" aria-label='Glossy Bag?'>
Add to Cart Button

The cart button is similar to a standard button, but we’re going to go out of our way to label it more clearly than other buttons:

<button aria-label="Add to Cart">Add to Cart</button>Expanded Product Content

Finally, the expanded content area is treated just like a typical content area. Depending on your product pages, however, it might be a good idea to separate your main content landmarks from your supplementary content landmarks. The tabs add an extra layer to the code here as well. Here’s how we’d do it in our example:

<div id="tabs" role='comlementary' aria-label="Expanded Content Area"> <ul role="tablist"> <li role="presentation"><a href="#more-info" id="tab-more-info" role="tab" aria-selected="true" tabindex="0">Product Info</a></li> </ul> <div id="more-info" role="tabpanel" aria-hidden="false" aria-labelledby="tab-more-info"> More product info... </div> </div>Adding ARIA to Category Pages

While product pages can be considered an alternative form of content page in most respects, a site’s category pages, also called Product Listing Pages (PLPs), are a whole different beast. They are operating as a large navigation structure, allowing users to sort through hundreds or even thousands of products.

This makes them increasingly complex, becoming even more so as additional layers of content and filters are added (we’ll talk about faceted navigation and filters in the next section). Let’s look at the two mains areas of our PLP outside of the filters: the product blocks and the pagination.

Here's our starting code frame:

<h1>Product Listing Page</h1> <div id='faceted-navigation'> <p>Color Sort</p> <a href="#">Red</a> <a href="#">Green</a> <a href="#">Black</a> <p>Size Sort</p> <a href="#">Large</a> <a href="#">Small</a> </div> <div id='product-listings'> <div id='product-block'> <h2>A Nice Bag</h2> <img src="bag.jpg" alt="A paper bag" /> <button>Add to cart</button> </div> ... </div> <div id='pagination'> 1 <a href="#">2</a> <a href="#">3</a> ... <a href="#">Last</a> </div>Handling Pagination

Pagination is the name given to the small links at the bottom of our product listings here. Typically, they’re represented by numbers or arrows, but they can come in various other forms. On the HTML side of things, pagination links look just like regular links. We’ll say that ours is controlling the product listings without redirecting to another page.

To make it known that it's controlling a content area in this way, we have to declare it as a controller, define what it is controlling, and then mark that content area as live. Here’s what that looks like in our case:

<div id='product-listings' role='main' aria-live='polite'> ... </div> <div id='pagination' role='navigation' aria-label='Pagination Links'> 1 <a href="#" aria-controls='product-listings'>2</a> <a href="#" aria-controls='product-listings'>3</a> ... <a href="#" aria-controls='product-listings'>Last</a> </div>

When we create our live area here, we utilize the "polite" setting that ARIA makes available. If your changes are pertinent and need to be addressed by the user quickly, or you need to prioritize among several live areas, you can use the value "assertive" as well.

Marking Up Repetitive Elements

A unique challenge that comes up with product landing pages is the intensive navigation complexity within the product listings themselves. From a visual perspective, it can be easy enough to group the information, using visual cues to determine what information applies to which product.

Doing so with ARIA has a few more layers than the previous applications we’ve covered. Marking a “buy now” button a standard button can create confusion when there are 20 of these buttons on a page. To solve this, we’ll need to create clear connections between each product and its related elements.

Here’s how we’ll do that:

<div id='product-listings' role='main' aria-live='polite'> <div id='product-block'> <h2 id='product-title'>A Nice Bag</h2> <img src="bag.jpg" alt="A paper bag" /> <button aria-labelledby='product-title'>Add to cart</button> </div> ... </div>

While this does help a bit with clarifying relations for the user, it's still not the best implementation. A better way would be to dynamically generate an aria-label by concatenating the product-title element with an additional phrase such as "add to cart".

Using ARIA With Faceted Navigation

Faceted navigation refers to the filters and options that are commonly shown on eCommerce sites, letting you narrow down your search results. These come in many flavors—from sizes to color and beyond. For our example, we’re going to make two assumptions:

  1. Our faceted navigation updates the products live on the page. This isn’t always the case, as sometimes eCommerce sites might generate a new page when a filter is applied, but we’ll be working as if the site updates content live.

  2. Our faceted navigation allows for the selection of multiple filters. Not every eCommerce site does this, and there are definitely cases where it shouldn’t be allowed. However, this creates an extra layer of complexity outside of the scope of this article.

Setting Up Your Controls

The HTML behind our filters is similar to that of pagination, appearing in the code as basic links. For our uses, though, the intent of the filters is to alter information that is currently on the page. Because of this, we’ll want to mark the entire container around the filters, making it clear that this is a controller for another area on the page:

<div id='faceted-navigation' role='navigation' aria-controls='product-listings'> <p>Color Sort</p> <a href="#" aria-label='Sort by Red'>Red</a> <a href="#" aria-label='Sort by Green'>Green</a> <a href="#" aria-label='Sort by Black'>Black</a> <p>Size Sort</p> <a href="#" aria-label='Sort by Large'>Large</a> <a href="#" aria-label='Sort by Small'>Small</a> </div>Defining Live Areas

Like pagination, these updates are happening live on the page. Because of this, we’ll want to mark the main content on our page as being “live”. Note that we did this previously in the pagination section, but we’ll be repeating the step here for consistency.

The code should look like this:

<div id='product-listings' role='main' aria-live='polite'> <div id='product-block'> <h2 id='product-title'>A Nice Bag</h2> <img src="bag.jpg" alt="A paper bag" /> <button aria-labelledby='product-title'>Add to cart</button> </div> ... </div>Testing Your Implementations

Our implementations are now all in place, so let’s put them through some tests. My favorite tools for doing so include Google’s Accessibility Developer Tools or IBM’s Dynamic Assistant Plugin, but depending on your project’s scale, you might need to create your own testing script.

If you need a tool that operates outside of Chrome, or just don’t prefer the two mentioned above, W3C has a list of other accessibility tools that are available.

Making eCommerce More Accessible

With these new additions to your ARIA toolset, you should now be able to appropriately mark up almost any eCommerce site. To ensure the best user experience with an eCommerce site, remember to keep your navigation as simple as possible, and express intent clearly.

Have further questions on this topic? Did I miss something important? Tell me in the comments below!

Categories: Web Design