emGee Software Solutions Custom Database Applications

Share this

Web Design

Now You See Me: How To Defer, Lazy-Load And Act With IntersectionObserver

Smashing Magazine - Mon, 01/22/2018 - 04:43
Once upon a time, there lived a web developer who successfully convinced his customers that sites should not look the same in all browsers, cared about accessibility, and was an early adopter of CSS grids. But deep down in his heart it was performance that was his true passion: He constantly optimized, minified, monitored, and even employed psychological tricks in his projects. Then, one day, he learned about lazy-loading images and other assets that are not immediately visible to users and are not essential for rendering meaningful content on the screen.
Categories: Web Design

Beginner's Guide to Angular 4: Components

Tuts+ Code - Web Development - Mon, 01/22/2018 - 04:00

Angular is a popular framework for creating front ends for web and mobile applications. It all started with AngularJS 1.x and then AngularJS 2, and now it's finally Angular, with the latest updates and bug fixes being worked on by the Angular team.

Components are an important part of an Angular web application. In this tutorial, you'll see how to get started with creating a web application using Angular, and you'll also get to know components.

Getting Started

Get started by installing Angular CLI using the node package manager (npm).

npm install -g @angular/cli

Once you have the Angular CLI installed, create a new Angular app using the CLI.

ng new angular-app

Navigate to the application folder and start the server.

cd angular-app ng serve

Point your browser to http://localhost:4200/ and you should have the default app running.

Angular App Structure

Navigate to the angular-app project folder and have a look at the project structure. Here is how it looks:

Every Angular app has a root module where you define the main component to load. In the default Angular app, the root module is defined inside the app.module.ts. When the AppModule loads, it checks which component is bootstrapped and loads that module. As seen in the app.module.ts, the module which is bootstrapped is AppComponent. The AppComponent component is defined in the file app.component.ts.

A component is defined using the @Component decorator. Inside the @Component decorator, you can define the component selector, the component template, and the related style. 

What Is an Angular Component?

Components are like the basic building block in an Angular application. Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component.

From the official docs:

Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.

The best way to understand something related to programming is by actually doing. So let's start by creating an Angular component for adding two numbers. Let's call it CalculatorComponent.

Creating the Calculator Component

Let's start by creating a component for our calculator. Inside the src/app folder, create a folder called calc. This is where our calc component will reside. Inside the calc folder, create a file called calc.component.html. This will be the template for our calculator component. Here is how it looks:

<h1> Calculator component </h1>

Create a file called calc.component.ts. This is where you'll define the calc component and specify the related metadata. You'll be defining the component using the @component decorator. To define the component, you need to import the component module from angular core.

import { Component } from '@angular/core';

Define the component by specifying the template, style, and selector. You'll also define a class to manage the template specified by the @component decorator. Here is how it looks:

import { Component } from '@angular/core'; @Component({ selector: 'calc', templateUrl: 'calc.component.html', styleUrls: ['calc.component.css'] }) export class CalcComponent { }

All styles related to the component template should be defined inside the file specified in the component decorator. So create a file called calc.component.css inside the calc folder. You'll put the style for the calculator component inside this file.

Now that you have your component ready, let's define the component inside the root module app.module.ts. 

First import the component inside the app.module.ts file and then include it in the declarations section. Here is how it looks after adding the CalcComponent:

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { CalcComponent } from './calc/calc.component' @NgModule({ declarations: [ AppComponent, CalcComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

As you can see in the root module app.module.ts, the AppComponent is the bootstrapped module and hence it will render by default. So, to view our calculator component, define it inside the app.component.html. Here is how the app.component.html file looks:

<div style="text-align:center"> <calc></calc> </div>

Save the above changes and start the server. You should be able to see the HTML content of the calculator component displayed.

Adding the Calculator Functionality

Let's start by adding a template for our Angular calculator. Add the following code to the calc.component.html file:

<div class="container"> <div class="header"> <h2> Calculator component </h2> </div> <div class="grid"> <div class="row"> <div class="col-6"> <div class="operation"> <div class="row"> <div class="col-12"> <input type="number" name="" placeholder="number"> </div> </div> <div class="row"> <div class="col-12"> <input type="number" name="" placeholder="number"> </div> </div> <div> <div class="col-12"> <button class="button"> Add </button> </div> </div> </div> </div> <div class="col-6"> <div class="result"> <span> Result </span> </div> </div> </div> </div> </div>

Add the following style to the calc.component.css file.

.grid{ width: 100% } .row{ width: 100%; display: flex; } .col-1 { width: 8.33%; } .col-2 { width: 16.66%; } .col-3 { width: 25%; } .col-4 { width: 33.33%; } .col-5 { width: 41.66%; } .col-6 { width: 50%; } .col-7 { width: 58.33%; } .col-8 { width: 66.66%; } .col-9 { width: 75%; } .col-10 { width: 83.33%; } .col-11 { width: 91.66%; } .col-12 { width: 100%; } .header{ width: 100%; background-color: #003A60; height: 100px; } .header h2{ line-height: 100px; color: #fff; } .button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } input{ border: none; border-bottom: 1px solid grey; width: 80%; margin: 0% 10%; padding: 5%; } .result{ background-color: #ddffff; width: 80%; margin: 20px 10px 10px 10px; height: 100px; border-left: 3px solid #2196F3; } .result span{ line-height: 100px; }

Save the above changes and you should be able to view the following user interface.

Let's add the ngModel directive to the above displayed input text boxes. Modify the calc.component.html code as shown below:

<div class="row"> <div class="col-12"> <input [(ngModel)]="number1" type="number" name="" placeholder="number"> </div> </div> <div class="row"> <div class="col-12"> <input [(ngModel)]="number2" type="number" name="" placeholder="number"> </div> </div>

As seen above, you have set the ngModel for the input text boxes to the variables number1 and number2. 

Let's define the variables inside the CalcComponent in the calc.component.ts file.

export class CalcComponent { public number1 : number; public number2 : number; }

Now, when the user types into the text boxes, the corresponding ngModel variable gets updated. You can check by displaying the variable in the component's template file.

<div class="result"> <span> Number 1 : {{number1}} Number 2 : {{number2}} </span> </div>

Save the changes and enter values inside the input boxes, and you should have the data updated inside the span.

Let's add a button click to the Add button which will calculate the sum of the number1 and number2 when clicked on the button.

Modify the HTML code as shown to include the click directive.

<button (click)="add()" class="button"> Add </button>

Define the add function inside the CalcComponent as shown:

import { Component } from '@angular/core'; @Component({ selector: 'calc', templateUrl: 'calc.component.html', styleUrls: ['calc.component.css'] }) export class CalcComponent { public number1 : number; public number2 : number; public result : number; public add(){ this.result = this.number1 + this.number2 } }

As seen in the above code, the result of the addition is being placed in a variable called result.

Let's modify the HTML template to display the result once the variable is set.

<div class="result"> <span> Result : {{result}} </span> </div>

Save the above changes and try to add two numbers by clicking on the Add button. You will have the result displayed in the user interface.

Wrapping It Up

In this tutorial, you saw how to get started with creating a web app using Angular 4. You learnt about Angular components and how to create one. You created a simple Angular component to add two numbers.

Source code from this tutorial is available on GitHub. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

Do let us know your thoughts, suggestions or any corrections in the comments below.

Categories: Web Design

Review: Wix Code for Quick Site and App Building

Wix Code is a new IDE (integrated development environment) created by Wix, a popular cloud-based website builder. Launched in December 2017, Wix Code gives web designers and developers advanced functionality...

The post Review: Wix Code for Quick Site and App Building appeared first on Onextrapixel.

Categories: Web Design

Monthly Web Development Update 1/2018: Browser Diversity, Ethical Design, And CSS Alignment

Smashing Magazine - Fri, 01/19/2018 - 06:17
I hope you had a great start into the new year. And while it’s quite an arbitrary date, many of us take the start of the year as an opportunity to try to change something in their lives. I think it’s well worth doing so, and I wish you the best of luck for accomplishing your realistic goals. I for my part want to start working on my mindfulness, on being able to focus, and on pursuing my dream of building an ethically correct, human company with Colloq that provides real value to users and is profitable by its users.
Categories: Web Design

Creating a Drop-Down Menu for Mobile Pages

Tuts+ Code - Web Development - Fri, 01/19/2018 - 04:00

This tutorial will teach you how to create and animate a hamburger menu icon and then attach an event listener through jQuery for triggering a drop-down menu.

I will be using Jade (Pug) and Sass instead of vanilla HTML and CSS. So you should at least have a basic knowledge of these templating engines.

Creating the Playground

We will start with the implementation of a simple playground. I will only be providing the Jade template along with Sass styling, since this is not the scope of the tutorial. You can take it and use it or you can come up with your own design.

Jade file:

body #container #header #body .content .left .right - for (i=1; i <= 5 ; i++ ) div( id="text" + i ) .content .left .right - for (j=6; j <= 10 ; j++ ) div( id="text" + j ) .content .left .right - for (k=11; k <= 15 ; k++ ) div( id="text" + k )

Sass file:

=flex() display: -webkit-box display: -moz-box display: -ms-flexbox display: -webkit-flex display: flex =transition($time) -webkit-transition: all $time ease -moz-transition: all $time ease -ms-transition: all $time ease -o-transition: all $time ease transition: all $time ease html, body margin: 0 padding: 20px 0 +flex() justify-content: center //----------------------------------// #container width: 320px height: 550px background-color: #ebebeb overflow: hidden #header height: 45px background-color: #9b9b9b position: relative #body padding: 0 20px padding-top: 40px +flex() flex-direction: column justify-content: flex-start .content +flex() flex-direction: row justify-content: flex-start margin-bottom: 25px .left width: 100px height: 100px margin-right: 15px background-color: #e1e1e1 .right @for $i from 1 through 15 #text#{$i} margin-top: 10px width: 50 + random(100) + px height: 10px background-color: #e1e1e1

Note: Here I created two mixins named flex and transition. Mixins make it easier to reuse some CSS rules by grouping them. Whenever I need to add display:flex with all vendor prefixes, I can just use +flex() instead, thanks to the mixin.

We will use this structure and build upon it for the rest of the tutorial.

The final result should look like this:

View the current code

Hamburger Menu Icon

Now it is time to create a simple yet attractive hamburger menu and animate it through CSS.

Add a new div inside #header and name it #hamburger. Then create two children divs inside #hamburger. They should have a common class and individual IDs.

#hamburger .strip#top .strip#bottom

Now we need to style the parent #hamburger div and the children divs with the common class of .strip.

#hamburger height: 100% width: 45 +flex() flex-direction: column justify-content: space-between padding-left: 20px

We set the height of the div equal to its parent div, which is #header, by defining the height: 100%. Also, we set a width value for this parent div, which will define its "clickable" region.

Next, we add flexbox with all vendor prefixes by using mixins, which we created earlier.

Since we want our .strip divs to be positioned vertically, we set flex-direction: column and then use justify-content: space-between in order to put space in between the .strip divs.

Then we need to push those divs towards each other by adding bottom and top padding to the respective divs.

#top margin-top: 17px #bottom margin-bottom: 17px

We also added padding-left: 20px in order to move the .strip divs further to the right.

The next thing is to style the strips. This is relatively easy by just defining the size and the color of the divs.

.strip width: 25px height: 2px background-color: #ffffff

The final result with the hamburger menu icon should look like this:

The next thing is to animate the menu icon so that when it is clicked, it should animate into a cross sign.

Animating the Hamburger Menu Icon

At this point, we are going to use basic jQuery to toggle some CSS classes.

Let's first create the CSS classes to be toggled.

We are going to utilize the translate and rotate settings of the transform property of CSS along with the transition property.

First, add transitions to both the #top and #bottom divs by using mixins with a specific timing parameter.

#top margin-top: 17px +transition(.25s) #bottom margin-bottom: 17px +transition(.25s)

Now we need to define the styling of the classes to be toggled.

We will be rotating and translating each .strip div individually, so we need to toggle different classes both for the #top and #bottom divs.

#top margin-top: 17px +transition(.25s) &.topRotate transform-origin: center transform: translateY(4px) rotateZ(45deg) #bottom margin-bottom: 17px +transition(.25s) &.bottomRotate transform-origin: center transform: translateY(-5px) rotateZ(-45deg)

Here we defined the styling for two different classes named .bottomRotate and .topRotate, which will be added to and removed from their respective reference divs, #top and #bottom.

Note that different sizing of the .strip class would result in a need for different translateY and rotateZ values in order to animate into a proper cross sign.

Class Toggling With jQuery

We defined how each .strip div will animate when the topRotate and bottomRotate classes are present. However, we have yet to attach an event listener to toggle those classes.

Create a new JavaScript file and use the following code to toggle the topRotate and bottomRotate classes to divs with #top and #bottom IDs respectively.

$(document).ready(function(){ $("#hamburger").click(function(){ $("#top").toggleClass("topRotate"); $("#bottom").toggleClass("bottomRotate"); }); })

We put all our code inside $(document).ready(function(){}) in order to wait for the whole page to be loaded before taking any action. 

When we click the #hamburger div, it will toggle the classes for divs with specific IDs.

Note: Do not forget to add the jQuery source file into your project.

View the current code

Creating the Menu List

The next step is to create a menu with list items.

Use the following structure under the #header:

#dropDown #background ul li Home li Blog li Projects li Authors li Jobs li Contact

So here we used the ul tag as the parent in order to group the items with li tags as children. Moreover, in order to create an expanding background animation, we also added a div with the ID of #background.

Let's style the ul and li elements first.

ul list-style: none padding: 0 margin: 0

Set the list-style to none in order to remove the bullets from the ul elements and also set both padding and margin to 0 in order to remove all predefined values.

Now style the li elements:

li //display: none background-color: #9b9b9b color: #ffffff font-family: 'Quicksand', sans-serif font-weight: lighter font-size: 15px padding: 20px padding-left: 60px &:after position: absolute content: '' left: 60px width: 60% height: 1px bottom: 4px background: rgba(255, 255, 255, 0.25) &:last-child:after width: 0

Here I commented out the display:none in order to be able to see the result. However, when animating, we will use it to hide the list elements initially.

I also added the after pseudo-element and styled it accordingly in order to separate each li element with a straight line. :last-child:after removes this line for the last li element.

View the current code 

Animating the Menu List

Now we are going to use some Sass control directives in order to add CSS keyframe animations with different attributes to each li element.

@keyframes drop 0% opacity: 0 transform: scale(1.3) 100% opacity: 1 transform: scale(1) @keyframes fold 0% opacity: 1 transform: scale(1) 100% opacity: 0 transform: scale(0.7)

Here we defined our keyframe animations drop and fold.

drop is for animating the opening of the menu list. The initial scaling is 30% more, and it scales back down to the original size as the transparency goes from 0 to 1. The opposite action takes place in fold.

Now we need to attach those keyframes to li elements. This part is where the Sass comes in handy.

@for $i from 1 through 6 li:nth-child(#{$i}) animation: name: fold duration: 80ms*(6-$i) + 1ms timing-function: ease-in-out fill-mode: forwards li.anim:nth-child(#{$i}) animation: name: drop duration: 100ms*$i timing-function: ease-in-out fill-mode: forwards

Here I used a for loop that goes from 1 to 6 with the index of $i.

Now we need to use this index to attach each animation to li elements with different durations.

First, consider the li.anim:nth-child(#{$i}) line.

Here we are grabbing the $ith child of the li element with class of anim.

We will be toggling this anim class. So, when it is added to li elements, the keyframe animation with the name of drop will take action. When it is removed, the fold animation will take action.

The next important thing is the duration attribute.

duration: 100ms*$i for the drop animation is extending the duration of the animation for each incrementing child number. So, when this code is compiled, the first li child will have duration: 100ms, and the last child will have duration: 600ms.

This will give the sense of animating each element one after another.

We do the same thing for the fold animation. This time, the last element should be animated faster, hence duration: 80ms*(6-$i) + 1ms. The 1ms added to the duration is due to the fact that when you set the duration to 0, some problems are likely to occur, and your animation might not work properly.

When we were styling the li element, I mentioned that we needed to use display:none in order to avoid undesired animation playing. If you don't set it to none, you will see that the fold animation plays once when the page is loaded.

If we set the display property to none, we won't see that, and then we need to show the li element before toggling the anim class.

We want our animations to play when we click the hamburger icon. So let's use some jQuery to set the display property of each li item to block and also toggle the anim class.

$(document).ready(function(){ $("#hamburger").click(function(){ $("#top").toggleClass("topRotate"); $("#bottom").toggleClass("bottomRotate"); $("li").show(); $("li").toggleClass("anim"); }); })

View the current code

You will notice that we can see the animation of each li element individually. However, we'd rather have an expanding menu feeling.

In order to fix that, we simply need to expand the height of a div. That div is #background, which we initially added when creating the ul and li elements.

#background width: 100% height: 0 background-color: #9b9b9b position: absolute +transition(.45s) &.expand height: 550px

We will be toggling the expand class in order to set the height attribute to 550px within .45s. Note that I used the transition mixin to define the transition with a specific time parameter.

Final Result 


Throughout this tutorial, we practiced how to use for loops within HTML and CSS through the Jade and Sass templating engines. On top of that, we created CSS keyframe animations and attached them with different duration attributes to specific HTML elements. Then we toggled classes with jQuery to control those animations.

Categories: Web Design

How To Internationalize Your WordPress Website

Smashing Magazine - Fri, 01/19/2018 - 00:43
On September 30th, 2017, the international WordPress community united for 24 hours to translate the WordPress ecosystem. For the third time, #WPTranslationDay fused an all-day translating marathon with digital and contributor day events designed to promote the value of creating accessible experiences for global users, better known as "localization". As an open-source community, we should all strive to localize our open-source contributions. Before you can transcribe your digital assets though, you have to internationalize your codebase.
Categories: Web Design

Introduction to Forms in Angular 4: Writing Custom Form Validators

Tuts+ Code - Web Development - Thu, 01/18/2018 - 04:00

This is the third part of the series on creating forms in Angular. In the first two tutorials, we used Angular's template-driven and model-driven approach to create forms. However, while detailing both the approaches, there was something that we didn't cover—custom validator functions. This tutorial will cover everything you need to know about writing custom validators that meet your requirements.


You don’t need to have followed part one or two of this series for part three to make sense. However, if you are entirely new to forms in Angular, you should head over to the first tutorial of this series and start from there. 

Otherwise, grab a copy of this code from our GitHub repo and use that as a starting point.  

Built-in Validators

Angular doesn't boast a huge built-in validator library. As of Angular 4, we have the following popular validators in Angular:

  • required
  • minlength
  • maxlength
  • pattern

There are actually a few more, and you can see the full list in the Angular docs

We can use the above built-in validators in two ways:

1. As directives in template-driven forms.

<input name="fullName" ngModel required>

2. As validators inside the FormControl constructor in model-driven forms.

name = new FormControl('', Validators.required)

If the above syntax doesn't make sense, follow my previous tutorials on building a signup form using a template-driven approach or a model-driven approach and then drop back!

The built-in form validators hardly cover all the validation use cases that might be required in a real-world application. For instance, a signup form might need to check whether the values of the password and confirm password control fields are equal and display an error message if they don't match. A validator that blacklists emails from a particular domain is another common example. 

Here is a fact: Template-driven forms are just model-driven forms underneath. In a template-driven form, we let the template take care of the model creation for us. The obvious question now is, how do you attach a validator to a form?

Validators are just functions. In a model-driven form, attaching validators to FormControl is straightforward. In a template-driven form, however, there is a bit more work to be done. In addition to the validator function, you will need to write a directive for the validator and create instances of the directive in the template.

Diving Into the Details

Although this has been already covered, we will go through a quick recap of the code for the signup form. First, here's the reactive approach.

app/signup-form/signup-form.component.ts // Use the formbuilder to build the Form model this.signupForm = this.fb.group({ email: ['',[Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]], password: this.fb.group({ pwd: ['', [Validators.required, Validators.minLength(8)]], confirmPwd: ['', [Validators.required, Validators.minLength(8) ]] }, { validator: PasswordMatch }), gender: ['', Validators.required], })

FormBuilder is a syntax sugar that creates the FormGroup and FormControl instances. A FormControl tracks the value and the validation status of an individual form element. A FormGroup, on the other hand, comprises a group of FormControl instances, and it tracks the value and validity of the whole group.

Here's the structure that we have been following:

FormGroup -> 'signupForm' FormControl -> 'email' FormGroup -> 'password' FormControl -> 'pwd' FormControl -> 'confirmPwd' FormControl -> 'gender'

Depending on the requirements, we can attach a validator to a FormControl or a FormGroup. An email blacklisting validator would require it to be attached to the FormControl instance of the email. 

However, for more complex validations where multiple control fields have to be compared and validated, it's a better idea to add the validation logic to the parent FormGroup. As you can see, password has a FormGroup of its own, and this makes it easy for us to write validators that check the equality of pwd and confirmPwd.

For the template-driven form, all that logic goes into the HTML template, and here is an example:

app/signup-form/signup-form.component.html<form novalidate (ngSubmit)="onFormSubmit(signupForm)" #signupForm="ngForm"> <!-- Email input block --> <input type="text" [ngModel] = "user.email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required> <!-- Password block --> <div ngModelGroup="password"> <input type="password" ngModel name="pwd" minlength ="8" required > <input type="password" class="form-control" ngModel name="confirmPwd" > </div> ... <!-- Select Gender block --> <select id="select" class="form-control" [ngModel] = "user.gender" name = "gender" required> </select> </form>

ngModel creates an instance of FormControl and binds it to a form control element. Similarly, ngModelGroup creates and binds a FormGroup instance to a DOM element. They share the same model domain structure discussed above. 

It's also interesting to note that FormControl, FormGroup, and FormArray extend the AbstractControl class. What this means is that the AbstractControl class is responsible for tracking the values of form objects, validating them, and powering other things such as pristine, dirty, and touched methods. 

Now that we are acquainted with both the form techniques, let's write our first custom validator.

Custom Validator Function for Model-Driven Forms

Validators are functions that take a FormControl/FormGroup instance as input and return either null or an error object. null is returned when the validation is successful, and if not, the error object is thrown. Here's a very basic version of a validation function. 

app/password-match.tsimport { FormGroup } from '@angular/forms'; export function passwordMatch( control: FormGroup):{[key: string]: boolean} { }

I've declared a function that accepts an instance of FormGroup as an input. It returns an object with a key of type string and a true/false value. This is so that we can return an error object of the form below:

{ mismatch: true }

Next, we need to get the value of the pwd and confirmPwd FormControl instances. I am going to use control.get() to fetch their values. 

export function passwordMatch (control: FormGroup):{[key: string]: boolean} { //Grab pwd and confirmPwd using control.get const pwd = control.get('pwd'); const confirmPwd = control.get('confirmPwd'); }

Now we need to make the comparison and then return either null or an error object.

app/password-match.tsimport { AbstractControl } from '@angular/forms'; export function passwordMatch (control: AbstractControl):{[key: string]: boolean} { //Grab pwd and confirmPwd using control.get const pwd = control.get('pwd'); const confirmPwd = control.get('confirmPwd'); // If FormControl objects don't exist, return null if (!pwd || !confirmPwd) return null; //If they are indeed equal, return null if (pwd.value === confirmPwd.value) { return null; } //Else return false return { mismatch: true }; }

Why did I replace FormGroup with AbstractControl? As you know, AbstractControl is the mother of all Form* classes, and it gives you more control over the form control objects. It has the added benefit that it makes our validation code more consistent.

Import the passwordMatch function in the SignupForm component and declare it as a validator for the password FormGroup instance.

app/password-match.tsimport { passwordMatch } from './../password-match'; . . . export class SignupFormComponent implements OnInit { ngOnInit() { // Use the formbuilder to build the Form model this.signupForm = this.fb.group({ ... password: this.fb.group({ pwd: ['', [Validators.required, Validators.minLength(8)]], confirmPwd: ['', [Validators.required, Validators.minLength(8) ]] }, { validator: passwordMatch }), ... }) } } Displaying the Errors

If you did everything right, password.errors?.mismatch will be true whenever the values of both the fields don't match.

{{ password.errors?.mismatch } json }}

Although there are alternative ways to display errors, I am going to use the ngIf directive to determine whether an error message should be displayed or not.

First, I am going to use ngIf to see if the password is invalid. 

<!-- Password error block --> <div *ngIf="(password.invalid && password.touched)"> </div>

We use password.touched to ensure that the user is not greeted with errors even before a key has been pressed.

Next, I am going to use the ngIf ="expression; then a else b" syntax to display the right error.

app/signup-form/signup-form.component.html <ng-container *ngIf="password.errors?.mismatch; then first else second"> </ng-container> <ng-template #first> Password do not match </ng-template> <ng-template #second> Password needs to be more than 8 characters </ng-template>

There you have it, a working model of the validator that checks for password equality.

Demo for Custom Validators in Model-Driven FormsCustom Validator Directive for Template-Driven Forms

We will be using the same validator function that we created for the model-driven form earlier. However, we don't have direct access to instances of FormControl/FormGroup in a template-driven form. Here are the things that you will need to do to make the validator work:

  1. Create a PasswordMatchDirective that serves as a wrapper around the passwordMatch validator function. We will be registering the directive as a validator using the NG_VALIDATORS provider. More on this later.
  2. Attach the directive to the template form control. 

Let's write the directive first. Here's what a directive looks like in Angular:

app/password-match.tsimport { AbstractControl } from '@angular/forms'; export function passwordMatch (control: AbstractControl):{[key: string]: boolean} { //Grab pwd and confirmPwd using control.get const pwd = control.get('pwd'); const confirmPwd = control.get('confirmPwd'); // If FormControl objects don't exist, return null if (!pwd || !confirmPwd) return null; //If they are indeed equal, return null if (pwd.value === confirmPwd.value) { return null; } //Else return false return { mismatch: true }; } //PasswordMatchDirective @Directive({ selector: '', providers: [ ] }) export class PasswordMatchDirective { }

The @Directive decorator is used to mark the class as an Angular directive. It accepts an object as an argument that specifies the directive configuration meta-data such as selectors for which the directive should be attached, and the list of Providers to be injected, etc. Let's fill in the directive meta-data:

app/password-match.ts@Directive({ selector: '[passwordMatch][ngModelGroup]', //1 providers: [ //2 { provide: NG_VALIDATORS, useValue: passwordMatch, multi: true } ] }) export class PasswordMatchDirective { }
  1. The directive is now attached to all input controls that have the attributes ngModelGroup and passwordMatch. 
  2. We extend the built-in validators using the NG_VALIDATORS provider. As previously mentioned, NG_VALIDATORS is a provider that has an extensible collection of validators. The passwordMatch function that we created earlier is declared as a dependency. The multi: true sets this provider to be a multi-provider. What this means is that we will be adding to the existing collection of validators provided by NG_VALIDATORS.

Now, add the directive to the declarations array in ngModule.

app/app.module.ts... import {PasswordMatchDirective} from './password-match'; @NgModule({ declarations: [ AppComponent, SignupFormComponent, PasswordMatchDirective ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Displaying Error Messages

To display the validation error messages, I am going to use the same template that we created for the model-driven forms.

<!-- Password error block --> <div *ngIf="(userPassword.invalid && userPassword.touched)"> <ng-container *ngIf="userPassword.errors?.mismatch; then first else second"> </ng-container> <ng-template #first> Password do not match </ng-template> <ng-template #second> Password needs to be more than 8 characters </ng-template> </div> Demo for Custom Validators in Template-Driven FormsConclusion

In this tutorial, we learned about creating custom Angular validators for forms in Angular. 

Validators are functions that return null or an error object. In model-driven forms, we have to attach the validator to a FormControl/FormGroup instance, and that's it. The procedure was a bit more complex in a template-driven form because we needed to create a directive on top of the validator function. 

If you're interested in continuing to learn more about JavaScript, remember to check out what we have in Envato Market.

I hope that you've enjoyed this series on Forms in Angular. I would love to hear your thoughts. Share them through the comments. 

Categories: Web Design

Learning Elm From A Drum Sequencer (Part 2)

Smashing Magazine - Thu, 01/18/2018 - 03:57
In part one of this two-part article, we began building a drum sequencer in Elm. We learned the syntax, how to read and write type-annotations to ensure our functions can interact with one another, and the Elm Architecture, the pattern in which all Elm programs are designed. In this conclusion, we’ll work through large refactors by relying on the Elm compiler, and set up recurring events that interact with JavaScript to trigger drum samples.
Categories: Web Design

Using page speed in mobile search ranking

Google Webmaster Central Blog - Wed, 01/17/2018 - 09:00

People want to be able to find answers to their questions as fast as possible — studies show that people really care about the speed of a page. Although speed has been used in ranking for some time, that signal was focused on desktop searches. Today we’re announcing that starting in July 2018, page speed will be a ranking factor for mobile searches.

The “Speed Update,” as we’re calling it, will only affect pages that deliver the slowest experience to users and will only affect a small percentage of queries. It applies the same standard to all pages, regardless of the technology used to build the page. The intent of the search query is still a very strong signal, so a slow page may still rank highly if it has great, relevant content.

We encourage developers to think broadly how about performance affects a user’s experience of their page and to consider a variety of user experience metrics. Although there is no tool that directly indicates whether a page is affected by this new ranking factor, here are some resources that can be used to evaluate a page’s performance.

  • Chrome User Experience Report, a public dataset of key user experience metrics for popular destinations on the web, as experienced by Chrome users under real-world conditions
  • Lighthouse, an automated tool and a part of Chrome Developer Tools for auditing the quality (performance, accessibility, and more) of web pages
  • PageSpeed Insights, a tool that indicates how well a page performs on the Chrome UX Report and suggests performance optimizations

As always, if you have any questions or feedback, please visit our webmaster forums.

Posted by Zhiheng Wang and Doantam Phan
Categories: Web Design

Understanding And Using REST APIs

Smashing Magazine - Wed, 01/17/2018 - 04:30
There’s a high chance you came across the term “REST API” if you’ve thought about getting data from another source on the internet, such as Twitter or Github. But what is a REST API? What can it do for you? How do you use it? In this article, you’ll learn everything you need to know about REST APIs to be able to read API documentations and use them effectively.
Categories: Web Design

A Comprehensive Guide To UX Research

Smashing Magazine - Wed, 01/17/2018 - 02:30
(This is a sponsored article.) Before embarking upon the design phase of any project, it’s critical to undertake some research so that the decisions you make are undertaken from an informed position. In this third article of my series for Adobe XD, I’ll be focusing on the importance of undertaking user research. Your job title might not be “design researcher”, but that doesn’t mean you shouldn’t at the very least inform yourself of your users and their needs by undertaking at least some initial scoping research before you embark upon a project.
Categories: Web Design

20 Best Tools to Generate Color Palettes

Everyone loves colors. Colors are among the most important elements of every design and artwork. As designers, we work with colors every day. However, it’s not an easy task...

The post 20 Best Tools to Generate Color Palettes appeared first on Onextrapixel.

Categories: Web Design

How Big Is That Box? Understanding Sizing In CSS Layout

Smashing Magazine - Tue, 01/16/2018 - 04:50
A key feature of Flexbox and Grid Layout is that they can deal with distributing available space between, around and inside grid and flex items. Quite often this just works, and we get the result we were hoping for without trying very hard. This is because the specifications attempt to default to the most likely use cases. Sometimes, however, you might wonder why something ends up the size that it is.
Categories: Web Design

Free Online Event On Building And Maintaining Design Systems

Smashing Magazine - Tue, 01/16/2018 - 03:25
(This is a sponsored article.) Everybody's talking about design systems, but they are more than just a trend. They are a best practice for design consistency and efficiency between designers and developers. Back in the day, only large companies could afford the effort of building and maintaining a design system. Nowadays, with the growth of new tools and processes, they have become much more feasible for companies of all sizes.
Categories: Web Design

How To Make A Drag-and-Drop File Uploader With Vanilla JavaScript

Smashing Magazine - Mon, 01/15/2018 - 04:12
It’s a known fact that file selection inputs are difficult to style the way developers want to, so many simply hide it and create a button that opens the file selection dialog instead. Nowadays, though, we have an even fancier way of handling file selection: drag and drop. Technically, this was already possible because most (if not all) implementations of the file selection input allowed you to drag files over it to select them, but this requires you to actually show the file element.
Categories: Web Design

10 Best WordPress Booking & Reservation Plugins

Tuts+ Code - Web Development - Mon, 01/15/2018 - 04:00

Businesses that rely on bookings and reservations can rely on WordPress to help them meet their online business goals.

From haircuts to hotels, and from health salons to consulting firms, these 10 best WordPress booking and reservations plugins from Envato Market are sure to help organizations level up their booking system.

These solutions include basic booking, Google Calendar integration, payments, and much, much more.

1. Bookly – #1 WordPress Booking Plugin

Bookly – #1 WordPress Booking Plugin is more than a WordPress booking and reservation plugin; it is full-featured, fully customizable, and much more.

The inclusion of SMS notifications, online payments, and Google Calendar sync sets it apart from many others.

"Automated online booking & scheduling for WordPress: fully customizable booking form with online payments, notifications, and Google Calendar sync."

Features also included:

  • the ability to book different services, with multiple staff members, at different prices
  • translation ready—includes 10 languages
  • easy payment integration
  • and more

The Bookly – #1 WordPress Booking Plugin is one of the most robust and flexible booking and reservation plugins you'll find.

2. Bookme - WordPress Booking Plugin

Bookme - WordPress Booking Plugin is a multi-purpose booking plugin that cuts away bloated features and delivers a streamlined booking system.

Customers can check availability, make appointments, and pay for services with this WordPress booking and reservation plugin.

Some booking types easily used:

  • consultant booking
  • default booking
  • group booking
  • and more

The number of staff members and services is unlimited, the appearance is fully customizable, and it supports custom fields and time slots.

The Bookme - WordPress Booking Plugin provides all the essential booking and reservation features you want and need, put together in a well-designed package.

3. WordPress WooCommerce Booking And Reservation Plugin

Bring WooCommerce and WordPress together to build a powerful booking and reservation system with the WordPress WooCommerce Booking And Reservation Plugin.

Easily create booking products. Multiple bookings for one day or one booking for many days—this WordPress booking and reservation plugin can handle it.

Manage your booking service attributes such as:

  • dates available
  • bookable periods
  • price multipliers
  • and more

Users can view your booking calendar, find availability, and even book more than one timeslot at a time.

The WordPress WooCommerce Booking And Reservation Plugin brings all the wonderful WooCommerce features and turns it into a powerful booking and reservation tool.

4. Webba Booking - WordPress Appointment & Reservation plugin

Webba Booking - WordPress Appointment & Reservation plugin is one of the best-looking WordPress booking and reservation plugins.

But it's not just about looks. This is a full-featured, robust system.

"Webba Booking is a powerful and easy to use WordPress booking plugin especially thought for Service Providers to optimize their time and for the comfort of their customers."

Features include:

  • online payments with PayPal and Stripe
  • multiple reservations in one session
  • CSV export
  • and more

There are many different notification mediums and types, not to mention reminders. So much is customizable, and the Google Calendar support is stellar.

Webba Booking - WordPress Appointment & Reservation plugin is easily one of the best WordPress booking and reservation plugins.

5. Event Booking Pro - WP Plugin [paypal or offline]

If you want a WordPress booking and reservation plugin that also keeps the offline aspect of booking in mind, then you'll want to consider the Event Booking Pro - WP Plugin [paypal or offline] plugin.

This includes an impressive feature set—and includes:

  • PayPal integration and coupon system
  • Google Maps and Calendar support
  • multiple tickets and sub-tickets
  • fully customizable
  • and much more

If the feature set isn't impressive enough for you, there are several different addons that can be purchased to extend it further.

If you're using WordPress for booking and reservations, consider Event Booking Pro - WP Plugin [paypal or offline].

6. Booki - WordPress Booking Calendar plugin for reservations and appointments

Appointments or reservations? Booki - WordPress Booking Calendar plugin for reservations and appointments can handle them both.

"Create and manage your appointments and reservations online with WordPress booking plugin Booki.""Schedule an appointment and book for a haircut, massage, accommodation, events, fitness, lesson, meeting, parking, rental, taxi, teacher, tickets and hundreds of other services."

Features include:

  • unlimited booking projects and service providers
  • enable online and offline payments
  • unlimited Google Calendar profiles
  • custom form fields
  • and more

The Booki - WordPress Booking Calendar plugin for reservations and appointments provides a unique feature set that's focused on offering important features needed for online booking for appointments and reservations.

7. WPBooking - Accommodation and Tour booking system - WordPress Plugin

With more of a focus on accommodations and tours, the WPBooking - Accommodation and Tour booking system - WordPress Plugin delivers its own flavor of a booking plugin.

It includes a complete list of features that are sure to make online booking and reservations a much smoother process.

"WP Booking is a complete booking solution for accommodation, tour and other services in a light, performance and easy to use plugin."

Features include:

  • create unlimited accommodations, tours, and extra services
  • easy to configure and include multi-language support
  • visitors can see booking history
  • and much more

With multiple payment methods and easy to use reporting, you'll be booking in no time at all with the WPBooking - Accommodation and Tour booking system - WordPress Plugin.

8. WP Quick Booking Manager Pro

Become a booking pro with the WP Quick Booking Manager Pro plugin.

This WordPress booking and reservation plugin provides a friendly booking interface and both multiple language and currency support.

Features include:

  • booking calendar and booking pages
  • easy to use and shortcode support
  • prevents double booking
  • fully responsive
  • and more

Manage your bookings from the WordPress Admin—no matter what you're booking.

The WP Quick Booking Manager Pro provides and quick and basic booking system with plenty of features.

9. Team Booking - WordPress booking system

Leverage the power of Google Calendar for your booking and reservations with the Team Booking - WordPress booking system.

This is "the only booking plugin that lets you use your Google Calendar for scheduling the availability!"

The more you look at the features, the more you realize this WordPress booking and reservation plugin has the greatest value.

A few features include:

  • Google Calendar and Google Maps support as well as translation ready
  • approval and cancel system for both provider and customers
  • customize reservation forms and email notifications
  • and much more

They even provide an API for your custom app.

The Team Booking - WordPress booking system is flexible, robust, and works great with Google Calendar.

10. WP Booking Calendar

If you don't know code, no problem. The WP Booking Calendar plugin has got you covered. This WordPress booking and reservation plugin is fully WPML compatible and includes the basic features you'll need.

"Booking Calendar helps you to easily add to your own WordPress website a powerful and simple booking system in a few minutes."

Features include:

  • customize the number of reservations allowed per slot
  • easy to use interface and CSV export support
  • use an unlimited number of calendars
  • and much more

The WP Booking Calendar gets the job scheduled.


There isn't a huge number of WordPress booking and reservation plugins out there, as the demand isn't very high. At the same time, those that are available in the Envato Market are solid plugins.

Did you find the plugin you were looking for?

If a WordPress booking plugin feature you want isn't listed here, you might consider coding your own. Envato Tuts+ has WordPress tutorials, eBooks, and courses. Try WordPress Plugin Development Essentials or maybe the WordPress Hacker's Guide to the Galaxy. Some helpful eBooks include Useful Tricks and Techniques for WordPress and Mastering WordPress.

Categories: Web Design

Review: Denko WordPress Theme for Your Business

In business, branding is everything. If you present yourself professionally on the web, customers will trust you more and you can generate leads more easily. Thus, an elegant business...

The post Review: Denko WordPress Theme for Your Business appeared first on Onextrapixel.

Categories: Web Design

Air Lookout Is The Side Project That Changed My Design Process Forever

Smashing Magazine - Fri, 01/12/2018 - 05:16
In February of 2015, I began working on an iOS app called Air Lookout. The goal of the app was to simplify and remove any obfuscation of air quality information. After over a year of working nights and weekends, the total net income since it launched in 2016 has been less than $1,000. Even with those numbers, I would relive every hour of work. The one thing that I can’t place a monetary value on is how the experience of creating Air Lookout has completely changed my mind on the process of design and development for every project I have worked on since.
Categories: Web Design

How to Auto Update WordPress Salts

Tuts+ Code - Web Development - Fri, 01/12/2018 - 04:00

If you've ever viewed the core configuration file (wp-config.php) for a WordPress site then you'll probably have noticed a section defining eight WordPress constants relating to security keys and salts:


Note: wp-config.php is located in the root folder of your WordPress installation by default.

These constants contain security keys and salts which are used internally by WordPress to add an additional layer of authentication and to enhance security.

WordPress uses cookies (rather than PHP sessions) to keep track of who is currently logged in. This information is stored in cookies in your browser.

To make sure that authentication details are as secure as possible, unique keys and salts are used to increase the level of cookie encryption. These are recommended to be long strings (typically 64 characters long) of random alphanumeric and symbol characters.

The AUTH_KEY, SECURE_AUTH_KEY, and LOGGED_IN_KEY security key constants were added in WordPress 2.6, which replaced a single all-in-one key first introduced in WordPress 2.5.

NONCE_KEY was added soon after, in WordPress 2.7. Corresponding salts AUTH_SALT, SECURE_AUTH_SALT, LOGGED_IN_SALT, and NONCE_SALT were added along with each security key, but it wasn't until WordPress 3.0 that they were added to wp-config.php.

Before WordPress 3.0, you could optionally add your own salt constant definitions to wp-config.php, otherwise they would be generated by WordPress and stored in the database.

While the four security key constants are required, if you remove the salt constants from the WordPress config file, leave them at their defaults, or any salt is found to be a duplicate of another, then WordPress retrieves the salt from the database instead.

For new WordPress sites, salts will be generated and stored in the database.

Initially Setting Your Security Keys and Salts

During installation, WordPress doesn't generate unique security keys/salts in wp-config.php. Instead, the same default message is entered for each constant.

If you've just installed WordPress on a remote server then it's recommended that you change the default message for each security key/salt constant to a proper and unique value. 

Sometimes, your host will do this for you if you install WordPress via a custom script. Even so, for peace of mind, you might want to update the security keys/salts anyway soon after installation is complete.

Why Update Keys and Salts?

Even after the security keys and salts have been initially set, it's a good idea to update them every so often. Anything you can do to make your site more secure is generally a good idea.

And even though it's highly unlikely that your passwords (together with security keys/salts) could be broken, updating them periodically makes sense as it safeguards against unforeseen circumstances such as your site backups being intercepted by unwanted third parties, etc.

How to Update Security Keys and Salts

So how do you actually update your security keys and salts? Let's look at a few different methods.

Manually Updating Keys and Salts

You could manually create new values for each constant, but this is rather tedious to do, especially if you have more than one WordPress site to update! Also, each key/salt might not be as secure as it could be.

Fortunately, the nice folks at WordPress have made this process very simple by providing an API to automatically generate the key/salt values for you. All you have to do is visit a secret key URL:


When the page loads, you'll be presented with unique strings for each constant, as shown below:

As you can see, each generated WordPress key/salt is a random sequence of 64 characters. Try refreshing the page a few times to satisfy yourself that the URL generates completely random keys/salts each time.

If you are developing your WordPress site locally then you can simply copy and paste the generated keys/salts directly into wp-config.php to replace the existing entries.

Tip: I'd recommend always using the URL above, which utilizes the secure HTTP protocol.

This will effectively eliminate the chance of anyone intercepting the generated keys/salts when they are returned to you before being displayed in the browser.

If your site is hosted on a remote server then to update the keys/salts you'll need to either access and edit wp-config.php via your server control panel, or via an FTP client that allows editing of remote files, such as FileZilla (free).

Using a Plugin to Update Keys and Salts

If the thought of manually editing remote server files sends your head into a spin then you might want to consider using a plugin instead. This is a very easy way to update your security keys/salts at the click of a button.

There are various plugins available to generate and update your security keys and salts. A relatively new plugin called Salt Shaker, released in October 2016, is a lightweight solution with the added bonus that you can schedule automatic updates of keys/salts to occur whenever you like. And best of all, it's free. Let's take a look at how to use it.

Download Salt Shaker from the WordPress repository or install it directly from your WordPress admin in the usual way. Go to Plugins > Add New and start typing Salt Shaker in the Search plugins... text box. When you see the plugin appear in the list, click Install Now.

After the plugin is installed, an Activate button will appear. Click this to finish setup.

Now that the plugin is active, we can test it. To access the plugin settings, go to Tools > Salt Shaker in the WordPress admin.

Here, we can update the security keys/salts immediately with a single mouse click. As soon as the Change Now button is clicked, a spinning icon appears to the right to indicate the plugin is updating wp-config.php. As soon as the icon disappears, you know the security keys/salts have been updated.

Overall, the plugin works very well and can potentially save you a lot of time, especially if you have multiple WordPress websites. I'd perhaps like to see a couple more options for choosing the time period intervals, such as three months and six months, to increase the plugin's flexibility.

Also, a message clearly stating when the keys/salts have been updated would be useful—as would a further plugin option to automatically redirect to the login page after the keys/salts have been updated.

Alternatively, we can check the Change WP Keys and Salts box and choose when the wp-config.php constants are updated. This is a really nice feature and basically allows you to forget about having to update security keys/salts. Just let the plugin do it all for you!

Remember though, whenever the security keys/salts are updated, you will be required to log in again. This is because cookies relating to logins are invalidated, and so users need to log back in again to update the cookie. 

Therefore, before changing your security keys/salts, it's a good idea to have your login information to hand so you aren't accidentally locked out of your site.

Using an Automation Script to Update Keys and Salts

If you don't want to use a plugin and you have a lot of remote WordPress sites then you could consider using a script to directly update the security keys/salts.

The downside to this is that you need to be proficient in scripting. However, there are several ready-made solutions available, so you don't necessarily have to code your own.

One such script, called WP-Salts-Update-CLI by Ahmad Awais, updates security keys/salts on your local computer or remote server.

To install this script on your computer (macOS only), open a terminal window and enter the following:

sudo wget -qO wpsucli https://git.io/vykgu && sudo chmod +x ./wpsucli && sudo install ./wpsucli /usr/local/bin/wpsucli

This will make an executable script globally available via the wpsucli command. You can run it on your local machine to actively search for all instances of WordPress config files and replace the security keys/salts with new values directly from the WordPress secret key API URL.

When running the script on a remote server, it's recommended to do so from the root folder, i.e. cd /, and then run wpsucli. For more details about the script, see the main information page


In this tutorial, we've covered what WordPress security keys/salts are and why it's important to update them periodically. We've also looked at various ways you can update them, from manually copy/pasting (if you have direct access to wp-config.php) to using a plugin to completely automate the process. If you're familiar with the command line then you can also use a custom script to update local/remote sites fairly easily.

The downside is that you still have to manually run scripts which can be easily forgotten, so rather than having to schedule this into your workflow, using a plugin to automate the process might be the best way to go.

Whatever method you choose, the important thing is to remember that you're adding another layer of security to your WordPress site(s), and anything you can do to achieve that with minimal effort can only be a good thing!

And if you're looking for other utilities to help you build out your growing set of tools for WordPress or for code to study and become more well-versed in WordPress, don't forget to see what we have available in Envato Market.

Categories: Web Design

Universal Principles Of User Experience Design

Smashing Magazine - Fri, 01/12/2018 - 01:48
(This is a sponsored article.) As designers working in an ever-changing field, it’s important that we develop an understanding of the timeless design principles that underpin everything we do. In the second article in my series for Adobe XD, I’ll explore the foundations that enable us to establish some universal principles of UX. These principles, which should sit at the heart of everything we design and build, are critical and will stand the test of time:
Categories: Web Design