Tag Archiv: tutorials

Take a Selfie With JavaScript

take-a-selfie-with-js

In this tutorial we are going to show you how to make a JavaScript photobooth app that takes images using the camera on your phone, laptop or desktop. We will showcase a number of awesome native APIs that allowed us to make our project without any external dependencies, third-party libraries or Flash – vanilla JavaScript only!

Note that this app uses experimental technologies that are not available in desktop and mobile Safari.

The App

To the end user our app is just an oversimplified version of the camera app you can find on any smartphone. It uses a hardware camera to take pictures – that’s it. Under the hood, however, a whole lot of JavaScript magic is going on. Here is a high-level overview:

  1. We access the camera input and get a video stream from it using the getUserMedia API.
  2. Project the camera stream onto a HTML video element.
  3. When the user wants to take a picture, we copy the current video frame and draw it on a canvas element.
  4. Transform the canvas into an image dataURL which then can be shown on the screen or downloaded as a PNG.

In the article below we will only look at the more interesting parts of the code. For the full source go to the Download button near the top of this page or checkout the demo on JSfiddle.

Keep in mind that the navigator.getUserMedia API is considered deprecated, but it still has pretty good browser support and is the only way to access the camera right now, until it’s future replacement – navigator.mediaDevices.getUserMedia gains wider browser support.

Demo on JSfiddle

Demo on JSfiddle

Accessing The Camera

JavaScript provides a native API for accessing any camera hardware in the form of the navigator.getUserMedia method. Since it handles private data this API work only in secure HTTPS connections and always asks for user permission before proceeding.

camera-permission

Permission Dialog In Desktop Chrome

If the user allows to enable his camera, navigator.getUserMedia gives us a video stream in a success callback. This stream consists of the raw broadcast data coming in from the camera and needs to be transformed into an actual usable media source with the createObjectURL method.

navigator.getUserMedia(
    // Options
    {
        video: true
    },
    // Success Callback
    function(stream){

        // Create an object URL for the video stream and
        // set it as src of our HTLM video element.
        video.src = window.URL.createObjectURL(stream);

        // Play the video element to show the stream to the user.
        video.play();
 
    },
    // Error Callback
    function(err){

        // Most common errors are PermissionDenied and DevicesNotFound.
        console.error(err);

    }
);

Taking a Still Photo

Once we have the video stream going, we can take snapshots from the camera input. This is done with a nifty trick that utilizes the mighty <canvas> element to grab a frame from the running video stream and save it in an <img> element.

function takeSnapshot(){

    var hidden_canvas = document.querySelector('canvas'),
        video = document.querySelector('video.camera_stream'),
        image = document.querySelector('img.photo'),

        // Get the exact size of the video element.
        width = video.videoWidth,
        height = video.videoHeight,

        // Context object for working with the canvas.
        context = hidden_canvas.getContext('2d');


    // Set the canvas to the same dimensions as the video.
    hidden_canvas.width = width;
    hidden_canvas.height = height;

    // Draw a copy of the current frame from the video on the canvas.
    context.drawImage(video, 0, 0, width, height);

    // Get an image dataURL from the canvas.
    var imageDataURL = hidden_canvas.toDataURL('image/png');

    // Set the dataURL as source of an image element, showing the captured photo.
    image.setAttribute('src', imageDataURL); 

}

The canvas element itself doesn’t even need to be visible in the DOM. We are only using its JavaScript API as a way to capture a still moment from the video.

Downloading The Photo

Of course, we not only want to take glorious selfies but we also want be able to save them for future generations to see. The easiest way to do this is with the download attribute for <a> elements. In the HTML the button looks like this:

<a id="dl-btn" href="#" download="glorious_selfie.png">Save Photo</a>

The download attribute transforms our anchor from a hyperlink into a download button. Its value represents the default name of the downloadable file, the actual file to download is stored in the href attribute, which as you can see is empty for now. To load our newly taken photo here, we can use the image dataURL from the previous section:

function takeSnapshot(){

    //...

    // Get an image dataURL from the canvas.
    var imageDataURL = hidden_canvas.toDataURL('image/png');

    // Set the href attribute of the download button.
    document.querySelector('#dl-btn').href = imageDataURL;
}

Now when somebody clicks on that button they will be prompted to download a file named glorious_selfie.png, containing the photo they took. With this our little experiment is complete!

Conclusion

We hope that you’ve learned a lot from this tutorial and that you now feel inspired to build some kick-ass photo apps. As always, feel free to ask questions or share ideas in the comment section below!

Learn TypeScript in 30 Minutes

learn-typescript-in-30

Today we’re going to take a look at TypeScript, a compile-to-JavaScript language designed for developers who build large and complex apps. It inherits many programming concepts from languages such as C# and Java that add more discipline and order to the otherwise very relaxed and free-typed JavaScript.

This tutorial is aimed at people who are fairly proficient in JavaScript but are still beginners when it comes to TypeScript. We’ve covered most of the basics and key features while including lots of examples with commented code to help you see the language in action. Let’s begin!


The Benefits of Using TypeScript

JavaScript is pretty good as it is and you may wonder Do I really need to learn TypeScript? Technically, you do not need to learn TypeScript to be a good developer, most people do just fine without it. However, working with TypeScript definitely has its benefits:

  • Due to the static typing, code written in TypeScript is more predictable, and is generally easier to debug.
  • Makes it easier to organize the code base for very large and complicated apps thanks to modules, namespaces and strong OOP support.
  • TypeScript has a compilation step to JavaScript that catches all kinds of errors before they reach runtime and break something.
  • The upcoming Angular 2 framework is written in TypeScript and it’s recommended that developers use the language in their projects as well.

The last point is actually the most important to many people and is the main reason to get them into TypeScript. Angular 2 is one of the hottest frameworks right now and although developers can use regular JavaScript with it, a majority of the tutorials and examples are written in TS. As Angular 2 expands its community, it’s natural that more and more people will be picking up TypeScript.

tscript-trend

Recent rise of TypeScript’s popularity, data from Google Trends.


1_Installation

Installing TypeScript

You will need Node.js and Npm for this tutorial. Go here if you don’t have them installed.

The easiest way to setup TypeScript is via npm. Using the command below we can install the TypeScript package globally, making the TS compiler available in all of our projects:

npm install -g typescript

Try opening a terminal anywhere and running tsc -v to see if it has been properly installed.

tsc -v
Version 1.8.10

2_text_editors

Text Editors With TypeScript Support

TypeScript is an open-source project but is developed and maintained by Microsoft and as such was originally supported only in Microsoft’s Visual Studio platform. Nowadays, there are a lot more text editors and IDEs that either natively or through plugins offer support for the TypeScript syntax, auto-complete suggestions, error catching, and even built-in compilers.

  • Visual Studio Code – Microsoft’s other, lightweight open-source code editor. TypeScript support is built in.
  • Official Free Plugin for Sublime Text.
  • The latest version of WebStorm comes with built in support.
  • More including Vim, Atom, Emacs and others.

Compiling to JavaScript

TypeScript is written in .ts files (or .tsx for JSX), which can’t be used directly in the browser and need to be translated to vanilla .js first. This compilation process can be done in a number of different ways:

  • In the terminal using the previously mentioned command line tool tsc.
  • Directly in Visual Studio or some of the other IDEs and text editors.
  • Using automated task runners such as gulp.

We found the first way to be easiest and most beginner friendly, so that’s what we’re going to use in our lesson.

The following command takes a TypeScript file named main.ts and translates it into its JavaScript version main.js. If main.js already exists it will be overwritten.

tsc main.ts

We can also compile multiple files at once by listing all of them or by applying wildcards:

# Will result in separate .js files: main.js worker.js.
tsc main.ts worker.ts    

# Compiles all .ts files in the current folder. Does NOT work recursively.
tsc *.ts

We can also use the --watch option to automatically compile a TypeScript file when changes are made:

# Initializes a watcher process that will keep main.js up to date.
tsc main.ts --watch

More advanced TypeScript users can also create a tsconfig.json file, consisting of various build settings. A configuration file is very handy when working on large projects with lots of .ts files since it somewhat automates the process. You can read more about tsconfig.json in the TypeScript docs here


Static Typing

A very distinctive feature of TypeScript is the support of static typing. This means that you can declare the types of variables, and the compiler will make sure that they aren’t assigned the wrong types of values. If type declarations are omitted, they will be inferred automatically from your code.

Here is an example. Any variable, function argument or return value can have its type defined on initialization:

var burger: string = 'hamburger',     // String 
    calories: number = 300,           // Numeric
    tasty: boolean = true;            // Boolean

// Alternatively, you can omit the type declaration:
// var burger = 'hamburger';

// The function expects a string and an integer.
// It doesn't return anything so the type of the function itself is void.

function speak(food: string, energy: number): void {
  console.log("Our " + food + " has " + energy + " calories.");
}

speak(burger, calories);

Because TypeScript is compiled to JavaScript, and the latter has no idea what types are, they are completely removed:

// JavaScript code from the above TS example.

var burger = 'hamburger',
    calories = 300, 
    tasty = true; 

function speak(food, energy) {
    console.log("Our " + food + " has " + energy + " calories.");
}

speak(burger, calories);

However, if we try to do something illegal, on compilation tsc will warn us that there is an error in our code. For example:

// The given type is boolean, the provided value is a string.
var tasty: boolean = "I haven't tried it yet";
main.ts(1,5): error TS2322: Type 'string' is not assignable to type 'boolean'.

It will also warn us if we pass the wrong argument to a function:

function speak(food: string, energy: number): void{
  console.log("Our " + food + " has " + energy + " calories.");
}

// Arguments don't match the function parameters.
speak("tripple cheesburger", "a ton of");
main.ts(5,30): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Here are some of the most commonly used data types:

  • Number – All numeric values are represented by the number type, there aren’t separate definitions for integers, floats or others.
  • String – The text type, just like in vanilla JS strings can be surrounded by ‘single quotes’ or “double quotes”.
  • Boolean – true or false, using 0 and 1 will cause a compilation error.
  • Any – A variable with this type can have it’s value set to a string, number, or anything else.
  • Arrays – Has two possible syntaxes: my_arr: number[]; or my_arr: Array<number>.
  • Void – Used on function that don’t return anything.

To see a list of all of the available types, go to the official TypeScript docs – here.


5_interfaces

Interfaces

Interfaces are used to type-check whether an object fits a certain structure. By defining an interface we can name a specific combination of variables, making sure that they will always go together. When translated to JavaScript, interfaces disappear – their only purpose is to help in the development stage.

In the below example we define a simple interface to type-check a function’s arguments:

// Here we define our Food interface, its properties, and their types.
interface Food {
    name: string;
    calories: number;
}

// We tell our function to expect an object that fulfills the Food interface. 
// This way we know that the properties we need will always be available.
function speak(food: Food): void{
  console.log("Our " + food.name + " has " + food.calories + " calories.");
}

// We define an object that has all of the properties the Food interface expects.
// Notice that types will be inferred automatically.
var ice_cream = {
  name: "ice cream", 
  calories: 200
}

speak(ice_cream);

The order of the properties does NOT matter. We just need the required properties to be present and to be the right type. If something is missing, has the wrong type, or is named differently, the compiler will warn us.

interface Food {
    name: string;
    calories: number;
}

function speak(food: Food): void{
  console.log("Our " + food.name + " has " + food.calories + " grams.");
}

// We've made a deliberate mistake and name is misspelled as nmae.
var ice_cream = {
  nmae: "ice cream", 
  calories: 200
}

speak(ice_cream);
main.ts(16,7): error TS2345: Argument of type '{ nmae: string; calories: number; } 
is not assignable to parameter of type 'Food'. 
Property 'name' is missing in type '{ nmae: string; calories: number; }'.

This is a beginners guide so we won’t be going into more detail about interfaces. However, there is a lot more to them than what we’ve mentioned here so we recommend you check out the TypeScript docs – here.


6_classes

Classes

When building large scale apps, the object oriented style of programming is preferred by many developers, most notably in languages such as Java or C#. TypeScript offers a class system that is very similar to the one in these languages, including inheritance, abstract classes, interface implementations, setters/getters, and more.

It’s also fair to mention that since the most recent JavaScript update (ECMAScript 2015), classes are native to vanilla JS and can be used without TypeScript. The two implementation are very similar but have their differences, TypeScript being a bit more strict.

Continuing with the food theme, here is a simple TypeScript class:

class Menu {
  // Our properties:
  // By default they are public, but can also be private or protected.
  items: Array<string>;  // The items in the menu, an array of strings.
  pages: number;         // How many pages will the menu be, a number.

  // A straightforward constructor. 
  constructor(item_list: Array<string>, total_pages: number) {
    // The this keyword is mandatory.
    this.items = item_list;    
    this.pages = total_pages;
  }

  // Methods
  list(): void {
    console.log("Our menu for today:");
    for(var i=0; i<this.items.length; i++) {
      console.log(this.items[i]);
    }
  }

} 

// Create a new instance of the Menu class.
var sundayMenu = new Menu(["pancakes","waffles","orange juice"], 1);

// Call the list method.
sundayMenu.list();

Anyone who has written at least a bit of Java or C# should find this syntax comfortably familiar. The same goes for inheritance:

class HappyMeal extends Menu {
  // Properties are inherited

  // A new constructor has to be defined.
  constructor(item_list: Array<string>, total_pages: number) {
    // In this case we want the exact same constructor as the parent class (Menu), 
    // To automatically copy it we can call super() - a reference to the parent's constructor.
    super(item_list, total_pages);
  }

  // Just like the properties, methods are inherited from the parent.
  // However, we want to override the list() function so we redefine it.
  list(): void{
    console.log("Our special menu for children:");
    for(var i=0; i<this.items.length; i++) {
      console.log(this.items[i]);
    }

  }
}

// Create a new instance of the HappyMeal class.
var menu_for_children = new HappyMeal(["candy","drink","toy"], 1);

// This time the log message will begin with the special introduction.
menu_for_children.list();

For a more in-depth look at classes in TS you can read the documentation – here.


7_generics

Generics

Generics are templates that allow the same function to accept arguments of various different types. Creating reusable components using generics is better than using the any data type, as generics preserve the types of the variables that go in and out of them.

A quick example would be a script that receives an argument and returns an array containing that same argument.

// The <T> after the function name symbolizes that it's a generic function.
// When we call the function, every instance of T will be replaced with the actual provided type.

// Receives one argument of type T,
// Returns an array of type T.

function genericFunc<T>(argument: T): T[] {    
  var arrayOfT: T[] = [];    // Create empty array of type T.
  arrayOfT.push(argument);   // Push, now arrayOfT = [argument].
  return arrayOfT;
}

var arrayFromString = genericFunc<string>("beep");
console.log(arrayFromString[0]);         // "beep"
console.log(typeof arrayFromString[0])   // String

var arrayFromNumber = genericFunc(42);
console.log(arrayFromNumber[0]);         // 42
console.log(typeof arrayFromNumber[0])   // number

The first time we called the function we manually set the type to string. This isn’t required as the compiler can see what argument has been passed and automatically decide what type suits it best, like in the second call. Although it’s not mandatory, providing the type every time is considered good practice as the compiler might fail to guess the right type in more complex scenarios.

The TypeScript docs include a couple of advanced examples including generics classes, combining them with interfaces, and more. You can find them here.


8_modules

Modules

Another important concept when working on large apps is modularity. Having your code split into many small reusable components helps your project stay organized and understandable, compared to having a single 10000-line file for everything.

TypeScript introduces a syntax for exporting and importing modules, but cannot handle the actual wiring between files. To enable external modules TS relies on third-party libraries: require.js for browser apps and CommonJS for Node.js. Let’s take a look at a simple example of TypeScript modules with require.js:

We will have two files. One exports a function, the other imports and calls it.

exporter.ts

var sayHi = function(): void {
    console.log("Hello!");
}

export = sayHi;

importer.ts

import sayHi = require('./exporter');
sayHi();

Now we need to download require.js and include it in a script tag – see how here. The last step is to compile our two .ts files. An extra parameter needs to be added to tell TypeScript that we are building modules for require.js (also referred to as AMD), as opposed to CommonJS ones.

tsc --module amd *.ts

Modules are quite complex and are out of the scope of this tutorial. If you want to continue reading about them head out to the TS docs – here.


9_declaration_files

Third-party Declaration Files

When using a library that was originally designed for regular JavaScript, we need to apply a declaration file to make that library compatible with TypeScript. A declaration file has the extension .d.ts and contains various information about the library and its API.

TypeScript declaration files are usually written by hand, but there’s a high chance that the library you need already has a .d.ts. file created by somebody else. DefinitelyTyped is the biggest public repository, containing files for over a thousand libraries. There is also a popular Node.js module for managing TypeScript definitions called Typings.

If you still need to write a declaration file yourself, this guide will get you started.


10_typescript_2

Upcoming Features in TypeScript 2.0

TypeScript is still under active development and is evlolving constantly. At the time of the writing of this tutorial the LTS version is 1.8.10, but Microsoft have already released a Beta for TypeScript 2.0. It’s available for public testing and you can try it out now:

npm install -g typescript@beta

It introduces some handy new concepts such as:

  • Non-nullable types flag which prevents some variables from having their vlaue set to null or underifned.
  • New improved system for getting declaration files directly with an npm install.
  • Control flow type analysis that catches errors previously missed by the compiler.
  • Some innovations in the module export/import syntax.

Another long-awaited feature is the ability to control the flow of asynchronous functions in an async/await block. This should be available in a future 2.1 update.

Further Reading

The amount of information in the official docs can be a bit overwhelming at first, but the benefits of going through it will be huge. Our tutorial is to be used as an introduction, so we haven’t covered all of the chapters from the TypeScript documentation. Here are some of the more useful concepts that we’ve skipped:

  • Namespaces – here.
  • Enums – here.
  • Advanced Types and Type Guards – here.
  • Writing JSX in TypeScript – here.

Conclusion

We hope you enjoyed this tutorial!

Do you have any thoughts on TypeScript and would you consider using it in your projects? Feel free to leave a comment below!

Quick Tip: Detecting Your Location With JavaScript

learn-git-in-30-minutes

Most modern devices are capable of detecting their own location either through GPS, WiFi, or IP geolocation. Developers can use this information to provide better search suggestions, nearby store locations, and implement all kinds of useful map interactions in their apps and websites.

In the article below we’re going to take a look at an easy, pure-JavaScript way to access a device’s whereabouts without relying on any external dependencies or third-party services. Let’s begin!

Location sources

JavaScript offers a simple, yet powerful tool for locating devices in the form of the Geolocation API. It consists of a small set of easy to use methods that can obtain the device position through all three of the previously mentioned services:

  • GPS – primarily on mobile devices, very accurate up to 10 meters.
  • WiFi – available on most internet connected devices, also very accurate.
  • IP geolocation – limited to region and often times unreliable, used as a worst-case scenario when the other two fail.

When geo data is requested the browser will try and use all three of the above options depending on what’s available. The results from the WiFi source are usually used as it is quicker than GPS and way more accurate than IP geolcation.

Using the Geolocation API

The Geolocation API has almost full cross-browser support, but to make sure that it’s accessible to our users, it’s a good idea before doing anything to check whether the geolocation object exists in the Window.navigator interface.

if (navigator.geolocation) {
  // geolocation is available
} 
else {
  // geolocation is not supported
}

Inside the navigator.geolocation object reside all of the methods for the API:

  • Geolocation.getCurrentPosition() – Determines the device’s current location.
  • Geolocation.watchPosition() – Listens for changes in the location and invokes a callback on every movement.
  • Geolocation.clearWatch() – Removes a watchPosition event handler.

Тhe getCurrentPosition() and watchPosition() methods are used in a nearly identical fashion. They both work asynchronously, trying to obtain the device position and depending on the outcome of the attempt call a success callback or an error callback if it’s provided.

navigator.geolocation.getCurrentPosition(

    // Success callback
    function(position) {

        /*
        position is an object containing various information about
        the acquired device location:

        position = {
            coords: {
                latitude - Geographical latitude in decimal degrees.
                latitude - Geographical longitude in decimal degrees. 
                altitude - Height in meters relative to sea level.
                accuracy - Possible error margin for the coordinates in meters. 
                altitudeAccuracy - Possible error margin for the altitude in meters. 
                heading - The direction of the device in degrees relative to north. 
                speed - The velocity of the device in meters per second.
            }
            timestamp - The time at which the location was retrieved.
        }
        */

    },

    // Optional error callback
    function(error){

        /* 
        In the error object is stored the reason for the failed attempt:

        error = {
            code - Error code representing the type of error 
                    1 - PERMISSION_DENIED
                    2 - POSITION_UNAVAILABLE
                    3 - TIMEOUT

            message - Details about the error in human-readable format.
        }
        */

    }
);

As you can see, using the Geolocation API is pretty straightforward. We just have to call the right method, wait for it to return the coordinates, and then do whatever we want with them.

User permission

Since the Geolocation API exposes deeply personal information, when an application tries to access it for the first time, a dialog pops up requesting permission. This ensures that users will not have their private data revealed unless they explicitly allow it.

Permission Dialog In Desktop Chrome

Permission Dialog In Chrome On Android

Permission Dialog In Chrome On Android

The browser usually takes care for displaying the dialog, but permission can also be requested programmatically by the developer. This is sometimes necessary, since once denied the original browser-generated dialog doesn’t show itself a second time.

Secure hosts

Another protective measure is the usage of an HTTPS connection. Due to a new web security policy, Google Chrome (both desktop and mobile versions) no longer allows non-secure hosts to run the Geolocation API. Instead, developers who want to use this feature are required to serve their apps over HTTPS, thus minimizing the risks of having people’s data stolen or abused.

You can read more about the issue in this Google Developers blog post.

Demo app

To demonstrate how the whole process works, we’ve built an oversimplified app showcasing some of the capabilities of the API. It consists of a button, which when pressed, grabs the device coordinates and feeds them to this GMaps plugin, pinpointing the location on the map.

findMeButton.on('click', function(){

    navigator.geolocation.getCurrentPosition(function(position) {

        // Get the coordinates of the current position.
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;

        // Create a new map and place a marker at the device location.
        var map = new GMaps({
            el: '#map',
            lat: lat,
            lng: lng
        });

        map.addMarker({
            lat: lat,
            lng: lng
        });

    });
    
});

The demo, as well as the full code are available on JSFiddle:

Demo on JSfiddle

Demo on JSfiddle

Conclusion

The Gelocation API is reliable and production ready, so we encourage you to play around with it and see what it’s capable of. If you’ve seen some original uses of this technology on the web, or you’ve made a cool project yourself, fell free to share it in the comment section below – we would love to see it!

Learn Git in 30 Minutes

learn-git-in-30-minutes

Git has exploded in popularity in recent years. The verison control system is used by huge open source projects like Linux with thousands of contributors, teams of various sizes, solo developers and even students.

Beginners are often terrified by all the cryptic commands and arguments that git requires. But you don’t need to know all of that to get started. You can begin by mastering a handful of the most often used ones, and then slowly build from there. And this is exactly what we will teach you today. Let’s begin!


basics

The basics

Git is a collection of command line utilities that track and record changes in files (most often source code, but you can track anything you wish). With it you can restore old versions of your project, compare, analyze, merge changes and more. This process is referred to as version control. There are a number of version control systems that do this job. You may have heard some of them – SVN, Marcurial, Perforce, CVS, Bitkeeper and more.

Git is decentralized, which means that it doesn’t depend on a central server to keep old versions of your files. Instead it works fully locally by storing this data as a folder on your hard drive, which we call a repository. However you can store a copy of your repository online, which makes it easy for multiple people to collaborate and work on the same code. This is what websites like GitHub and BitBucket are used for.

1. Installing Git

Installing Git on your machine is straightforward:

  • Linux – Simply open up a new terminal and install git via your distribution’s package manager. For Ubuntu the command is: sudo apt-get install git-all
  • Windows – we recommend git for windows as it offers both a GUI client and a BASH comand line emulator.
  • OS X – The easiest way is to install homebrew, and then just run brew install git from your terminal.

If you are an absolute beginner, then a graphical git client is a must. We recommend GitHub Desktop and Sourcetree, but there are many other good and free ones online. Getting to know the basic git commands is still important even if you use a GUI app, so for the remaining of this lesson, this will be our only focus.

2. Configuring Git

Now that we’ve installed git on our computer, we will need to add some quick configurations. There are a lot of options that can be fiddled with, but we are going to set up the most important ones: our username and email. Open a terminal and run these commands:

$ git config --global user.name "My Name"
$ git config --global user.email myEmail@example.com

Every action we do in Git will now have a stamp with our name and address on it. This way users always know who did what and everything is way more organized.

3. Creating a new repository – git init

As we mentioned earlier, git stores its files and history directly as a folder in your project. To set up a new repository, we need to open a terminal, navigate to our project directory and run git init. This will enable Git for this particular folder and create a hidden .git directory where the repository history and configuration will be stored.

Create a folder on your Desktop called git_exercise, open a new terminal and enter the following:

$ cd Desktop/git_exercise/
$ git init

The command line should respond with something along the lines of:

Initialized empty Git repository in /home/user/Desktop/git_exercise/.git/

This means that our repo has been successfully created but is still empty. Now create a simple text file called hello.txt and save it in the git_exercise folder.

4. Checking the status – git status

Git status is another must-know command that returns information about the current state of the repository: is everything up to date, what’s new, what’s changed, and so on. Running git status in our newly created repo should return the following:

$ git status

On branch master

Initial commit

Untracked files:
  (use "git add ..." to include in what will be committed)

	hello.txt

The returned message states that hello.txt is untracked. This means that the file is new and Git doesn’t know yet if it should keep track of the changes happening to that file or just ignore it. To acknowledge the new file, we need to stage it.

5. Staging – git add

Git has the concept of a “staging area”. You can think of this like a blank canvas, which holds the changes which you would like to commit. It starts out empty, but you can add files to it (or even single lines and parts of files) with the git add command, and finally commit everything (create a snapshot) with git commit.

In our case we have only one file so let’s add that:

$ git add hello.txt

If we want to add everything in the directory, we can use:

$ git add -A

Checking the status again should return a different response from before.

$ git status

On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached ..." to unstage)

	new file:   hello.txt

Our file is ready to be commited. The status message also tells us what has changed about the files in the staging area – in this case its new file, but it can be modified or deleted, depending on what has happened to a file since the last git add.

6. Commiting – git commit

A commit represents the state of our repository at a given point in time. It’s like a snapshot, which we can go back to and see how thing were when we took it.

To create a new commit we need to have at least one change added to the staging area (we just did that with git add) and run the following:

$ git commit -m "Initial commit."

This will create a new commit with all the changes from the staging area (adding hello.txt). The -m "Initial commmit" part is a custom user-written description that summarizes the changes done in that commit. It is considered a good practice to commit often and always write meaningful commit messages.


remotes

Remote repositories

Right now our commit is local – it exist only in the .git folder. Although a local repository is useful by itself, in most cases we will want to share our work and deploy it to a server or a repository hosting service.

1. Connecting to a remote repository – git remote add

In order to upload something to a remote repo, we first have to establish a connection with it. For the sake of this tutorial our repository’s address will be https://github.com/tutorialzine/awesome-project. We advise you to go ahead and create your own empty repository at GitHub, BitBucket or any other service. The registration and setup may take a while, but all services offer good step-by-step guides to help you.

To link our local repository with the one on GitHub, we execute the following line in the terminal:

# This is only an example. Replace the URI with your own repository address.
$ git remote add origin https://github.com/tutorialzine/awesome-project.git

A project may have many remote repositories at the same time. To be able to tell them apart we give them different names. Traditionally the main remote repository in git is called origin.

2. Uploading to a server – git push

Now it’s time to transfer our local commits to the server. This process is called a push, and is done every time we want to update the remote repository.

The Git command to do this is git push and takes two parameters – the name of the remote repo (we called ours origin) and the branch to push to (master is the default branch for every repo).

$ git push origin master

Counting objects: 3, done.
Writing objects: 100% (3/3), 212 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/tutorialzine/awesome-project.git
 * [new branch]      master -> master

Depending on the service you’re using, you will need to authenticate yourself for the push to go through. If everything was done correctly, when you go in your web browser to the remote repository created earlier, hello.txt should be available there.

3. Cloning a repository – git clone

At this point, people can see and browse through your remote repository on Github. They can download it locally and have a fully working copy of your project with the git clone command:

$ git clone https://github.com/tutorialzine/awesome-project.git

A new local respository is automatically created, with the github version configured as a remote.

4. Getting changes from a server – git pull

If you make updates to your repository, people can download your changes with a single command – pull:

$ git pull origin master

From https://github.com/tutorialzine/awesome-project
 * branch            master     -> FETCH_HEAD
Already up-to-date.

Since nobody else has commited since we cloned, there weren’t any changes to download.


Branches

When developing a new feature, it is considered a good practice to work on a copy of the original project, called a branch. Branches have their own history and isolate their changes from one another, until you decide to merge them back together. This is done for a couple of reasons:

  • An already working, stable version of the code won’t be broken.
  • Many features can be safely developed at once by different people.
  • Developers can work on their own branch, without the risk of their codebase changing due to someone else’s work.
  • When unsure what’s best, multiple versions of the same feature can be developed on separate branches and then compared.

1. Creating new branches – git branch

The default branch of every repository is called master. To create additional branches use the git branch <name> command:

$ git branch amazing_new_feature

This just creates the new branch, which at this point is exactly the same as our master.

2. Switching branches – git checkout

Now, when we run git branch,  we will see there are two options available:

$ git branch
  amazing_new_feature
* master

Master is the current branch and is marked with an asterisk. However, we want to work on our new amazing features, so we need to switch to the other branch. This is done with the git checkout command, expecting one parameter – the branch to switch to.

$ git checkout amazing_new_feature

3. Merging branches – git merge

Our “amazing new feature” is going to be just another text file called feature.txt. We will create it, add it, and commit it.

$ git add feature.txt
$ git commit -m "New feature complete."

The new feature is complete, we can go back to the master branch.

$ git checkout master

Now, if we open our project in the file browser, we’ll notice that feature.txt has disappeared. That’s because we are back in the master branch, and here feature.txt was never created. To bring it in, we need to git merge the two branches together, applying the changes done in amazing_new_feature to the main version of the project.

git merge amazing_new_feature

The master branch is now up to date. The awesome_new_feature branch is no longer needed and can be removed.

git branch -d awesome_new_feature

 advanced

Advanced

In the last section of this tutorial, we are going to take a look at some more advanced techniques that are very likely to come in handy.

1. Checking difference between commits

Every commit has it’s unique id in the form of a string of numbers and symbols. To see a list of all commits and their ids we can use git log:

$ git log

commit ba25c0ff30e1b2f0259157b42b9f8f5d174d80d7
Author: Tutorialzine
Date:   Mon May 30 17:15:28 2016 +0300

    New feature complete

commit b10cc1238e355c02a044ef9f9860811ff605c9b4
Author: Tutorialzine
Date:   Mon May 30 16:30:04 2016 +0300

    Added content to hello.txt

commit 09bd8cc171d7084e78e4d118a2346b7487dca059
Author: Tutorialzine
Date:   Sat May 28 17:52:14 2016 +0300

    Initial commit

As you can see the ids are really long, but when working with them it’s not necessary to copy the whole thing – the first several symbols are usually enough.
To see what was new in a commit we can run git show [commit]:

$ git show b10cc123

commit b10cc1238e355c02a044ef9f9860811ff605c9b4
Author: Tutorialzine
Date:   Mon May 30 16:30:04 2016 +0300

    Added content to hello.txt

diff --git a/hello.txt b/hello.txt
index e69de29..b546a21 100644
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+Nice weather today, isn't it?

To see the difference between any two commits we can use git diff with the [commit-from]..[commit-to] syntax:

$ git diff 09bd8cc..ba25c0ff

diff --git a/feature.txt b/feature.txt
new file mode 100644
index 0000000..e69de29
diff --git a/hello.txt b/hello.txt
index e69de29..b546a21 100644
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+Nice weather today, isn't it?

We’ve compared the first commit to the last one, so we see all the changes that have ever been made.

2. Fixing a commit

If you notice that you’ve made a typo in your commit message, or you’ve forgotten to add a file and you see right after you commit, you can easily fix this with git commit --amend.  This will add everything from the last commit back to the staging area, and attempt to make a new commit. This gives you a chance to fix your commit message or add more files to the staging area.

For more complex fixes that aren’t in the last commit (or if you’ve pushed your changes already), you’ve got to use git revert. This will take all the changes that a commit has introduced, reverse them, and create a new commit that is the exact opposite.

The newest commit can be accessed by the HEAD alias.

$ git revert HEAD

For other commits it’s best to use an id.

$ git revert b10cc123

When reverting older commits, keep in mind that merge conflicts are very likely to appear. This happens when a file has been altered by another more recent commit, and now Git cannot find the right lines to revert, since they aren’t there anymore.

3. Resolving Merge Conflicts

Apart from the scenario depicted in the previous point, conflicts regularly appear when merging branches or pulling someone else’s work. Sometimes conflicts are handled automatically by git, but other times the person dealing with them has to decide (and usually handpick) what code stays and what is removed.

Let’s look at an example where we’re trying to merge two branches called john_branch and tim_branch. Both John and Tim are writing in the same file a function that displays all the elements in an array.

John is using a for loop:

// Use a for loop to console.log contents.
for(var i=0; i<arr.length; i++) {
    console.log(arr[i]);
}

Tim prefers forEach:

// Use forEach to console.log contents.
arr.forEach(function(item) {
    console.log(item);
});

They both commit their code on their respective branch. Now if they try to merge the two branches they will see the following error message:

$ git merge tim_branch 

Auto-merging print_array.js
CONFLICT (content): Merge conflict in print_array.js
Automatic merge failed; fix conflicts and then commit the result.

Git wasn’t able to merge the branches automatically, so now it’s up to the devs to manually resolve the conflict. If they open the file where the conflict resides, they’ll see that Git has inserted a marker on the conflicting lines.

<<<<<<< HEAD
// Use a for loop to console.log contents.
for(var i=0; i<arr.length; i++) {
    console.log(arr[i]);
}
=======
// Use forEach to console.log contents.
arr.forEach(function(item) {
    console.log(item);
});
>>>>>>> Tim's commit.

Above the ===== we have the current HEAD commit, and below the conflicting one. This way we can clearly see the differences, and decide which is the better version, or write a new one all together. In this situation we go for the latter and rewrite the whole thing, removing the markers to let Git know we’re done.

// Not using for loop or forEach.
// Use Array.toString() to console.log contents.
console.log(arr.toString());

When everything is set, a merge commit has to be done to finish the process.

$ git add -A
$ git commit -m "Array printing conflict resolved."

As you can see this process is quite tiresome and can get extremely hard to deal with in large projects. Most developers prefer to resolve conflicts with the help of a GUI client, which makes things much easier.

4. Setting up .gitignore

In most projects there are files or entire folders that we don’t want to ever commit. We can make sure that they aren’t accidentally included in our git add -A by creating a .gitignore file:

  1. Manually create a text file called .gitignore and save it in your project’s directory.
  2. Inside, list the names of files/directories to be ignored, each on a new line.
  3. The .gitignore itself has to be added, committed and pushed, as it is just like any other file in the project.

Good examples for files to be ignored are:

  • log files
  • task runner builds
  • the node_modules folder in node.js projects
  • folders created by IDEs like Netbeans and IntelliJ
  • personal developer notes

A .gitignore banning all of the above will look like this:

*.log
build/
node_modules/
.idea/
my_notes.txt

The slash at the end of some of the lines signals that this is a folder and we are ignoring everything inside it recursively. The asterisk serves it’s usual function as a wild card.


Conclusion

This ends our tutorial on git! We tried our best to bring you only the most important information you need, presented as short and concise as possible.

Git is quite complex and has a lot more features and tricks to offer. If you wish to find out more, here are some learning resources we recommend:

  • The official Git docs, including a whole book and video lessons – here.
  • Getting git right – Atlassian’s collection of tutorials and articles – here.
  • A list of GUI clients – here.
  • Git cheat sheet (PDF) – here.

5 Practical Examples For Learning Vue.js

vue1

We’ve already covered Angular.js and React in previous articles but there is a new frontend library that we think is worth your time. It’s called Vue.js and it has gathered a large community of enthusiastic developers.

The philosophy behind Vue.js is to provide the simplest possible API for creating real-time, two-way data binding between the view (HTML) and the model (a JavaScript object). As you will see in the following examples, the library holds true to that idea and working with it is effortless and enjoyable, without compromising on any functionality.

Getting Started

The easiest way to install Vue.js is to simply include it with a <script> tag at the end of your HTML’s body. The entire library is located in a single JavaScript file which you can download from the official website or import directly via CDN:

<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>

If you want to use the library in a Node.js project, vue is available as an npm module. There is also an official CLI, which allows users to quickly setup their whole project based on premade template builds.

Below are five editors containing example apps we’ve built for you. The code has lots of comments and is separated in tabs for each file, making it really easy to follow. The editors have Vue.js built-in so don’t be afraid to experiment. Also, you can download an archive containing all the examples from the Download button near the top of this article.

1. Navigation Menu

To kick things off we’re going to build a simple navigation bar. There are a few basic components almost every Vue.js app need to have. They are:

  • The model, or in other words our app’s data. In Vue.js this is simply a JavaScript object containing variables and their initial values.
  • An HTML template, the correct terminology for which is view. Here we chose what to display, add event listeners, and handle different usages for the model.
  • ViewModel – a Vue instance that binds the model and view together, enabling them to communicate with each other.

The idea behind these fancy words is that the model and the view will always stay in sync. Changing the model will instantly update the view, and vice versa. In our first example this is shown with the active variable, representing which menu item is currently selected.

(Play with our code editor on Tutorialzine.com)

As you can see working with the library is pretty straightforward. Vue.js does a lot of the work for us and provides familiar, easy to remember syntax:

  • simple JavaScript object for all the options
  • {{double brackets}} for templating
  • v-something inline attributes for adding functionality directly in the HTML.

2. Inline Editor

In the previous example our model had only a couple of predefined values.  If we want to give the users the ability to set any data, we can do two-way binding and link together an input field with a model property.  When text is entered, it is automatically saved in the text_content model, which then causes the view to update.

(Play with our code editor on Tutorialzine.com)

Another thing to note in the above code is the v-if attribute . It show or hides a whole element depending on the truthfulness of a variable. You can read more about it here.

3. Order Form

This example illustrates multiple services and their total cost. Since our services are stored in an array, we can take advantage of the v-for directive to loop through all of the entries and display them. If a new element is added to the array or any of the old ones is changed, Vue.js will automatically update and show the new data.

(Play with our code editor on Tutorialzine.com)

To display the prices in a correct format we use one of the available filters that come built-in with Vue.js. They allow us to lazily modify the model data – in this case the currency filter is perfect, as it adds a dollar sign and proper number decimals. Just like in Angular filters are applied using the | syntax – {{ some_data | filter }}.

4. Instant Search

Here we will create an app, that exhibits some of the articles on our website. The app will also have a search field allowing us to filter which articles are displayed.  There is a filterBy filter available, but it doesn’t do exactly what we need it to, so instead we will be creating our own custom filter.

(Play with our code editor on Tutorialzine.com)

The input field is bind to the searchString model. When text is entered the model is instantly updated and passed on to the searchFor filter. This way we can create a real-time search without having to worry about rendering or setting up event listeners – Vue.js handles all that!

5. Switchable Grid

In our last example we will demonstrate a common scenario where a page has different layout modes. Just like in the previous app we will be showing a list of articles from tutorialzine.com stored in an array.

By pressing one of the buttons in the top bar you can switch between a grid layout containing large images, and a list layout with smaller images and text.

(Play with our code editor on Tutorialzine.com)

Conclusion

There is a lot more to Vue.js than what we’ve showcased in these examples. The library also offers animations, custom components and all sorts of other features. We recommend you check out the excellent official documentation which is full of information and helpful snippets.

Having troubles deciding whether Vue.js is the right library for your project? The following links will be of great help to you:

  • An official, detailed comparison with other frameworks – here.
  • TodoMVC – a website where the same app is recreated with many different frameworks.
  • Our articles where we’ve done similar examples using React and Angular.js.

Thanks for reading!

Quick Tip: The Easiest Way To Make Responsive Headers

quick-tip-responsive-headers

Making pretty, responsive, headers is always a tricky process. Until now you needed to use floats or other complicated tricks and you even had to manually adjust pixel values. But not any more!

The technique we are about to show you relies on the powerful flexbox layout mode to do all the dirty work for you. It uses just a handful of CSS properties to create a header that is properly aligned and looks good on all screen sizes, while leaving the code cleaner and less hacky.

The Technique

In our demonstrative example we’ve built a header, which is separated in three sections with typical header content nested within them:

  • Left section – The company logo.
  • Middle section – Various hyperlinks.
  • Right section – A button.

Below you can check out a simplified version of the code.

In the first tab is the HTML where we group the sections in separate div tags. This makes it easier for CSS rules to be applied and generally produces a more organised code.

In the other tab is the CSS, which is just a couple of lines, does the entire job of finding the right places for the each of the sections.

Click the Run button to open up a live demo. You can test the responsiveness by resizing the frame:

<header>
	<div class="header-left">CoolLogo</div>
	<div class="header-center">
		<ul>
			<li><a href="#">Our products</a></li>
			<li><a href="#">Pricing</a></li>
			<li><a href="#">Blog</a></li>
		</ul>
	</div>
	<div class="header-right"><button>Buy now</button></div>
</header>
header{
	/* Enable flex mode. */
	display: flex; 
	
	/* Spread out the elements inside the header. */
	justify-content: space-between;

	/* Align items vertically in the center. */
	align-items: center;
}
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Easiest Way To Make Responsive Headers</title>
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>

<style>
*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body{
	font: normal 16px sans-serif;
	padding: 0 10%;
	background: #eee;
}

body .container{
	max-width:1200px;
	margin:0 auto;
}

/*	Header	*/

header{
	/* Enable flex mode. */
	display: flex; 
	/* Spread out the elements inside the header. */
	justify-content: space-between;
	/* Align items vertically in the center. */
	align-items: center;

	padding: 40px 100px;
	color: #fff;
	background-color: #488EAD;
}

.header-left{
	font: normal 28px 'Fugaz One', cursive;
}

.header-left span{
	color: #EAD314;
}

.header-center ul{
	list-style: none;
}

.header-center ul li{
	display: inline-block;
	margin: 0 15px;
}

.header-center ul li a{
	text-decoration: none;
	color: #fff;
	cursor: pointer;
	font-weight: bold;
}

.header-right button{
    color: #fff;
    cursor: pointer;
    font-weight: 800;
    text-transform: uppercase;
    padding: 12px 30px;
    border: 2px solid #FFFFFF;
    border-radius: 4px;
    background-color: transparent;
}

.header-right button:hover {
    background-color: rgba(255,255,255,0.1);
}

/*	Main content	*/

.main-content{
	padding: 60px 100px;
	background-color: #fff;
    line-height: 1.5;
    color: #444;
}

.main-content h2{
	margin-bottom: 38px;
}

.main-content p{
	margin: 30px 0;
}


.main-content .placeholder{
	margin: 40px 0;
	height:380px;
	background-color: #e3e3e3;
}


/*	Media queries	*/

@media (max-width: 1200px){
	header{
		padding: 40px 60px;
	}

	.main-content{
		padding: 100px 60px;
	}

	body {
	    padding: 0 5%;
	}
}

@media (max-width: 1000px){
	header{
		/* Reverse the axis of the header, making it vertical. */
		flex-direction: column;
		/* Align items to the begining (the left) of the header. */
		align-items: flex-start;
	}

	header > div{
		margin: 12px 0;
	}

	.header-center ul li{
		margin: 0 15px 0 0;
	}

}

@media (max-width: 600px){
	body {
	    padding: 0 10px;
	}

	.header-left{
		margin-top:0;
	}

	header {
	    padding: 30px;
	}

	.main-content{
		padding:30px;
	}
}


</style>
</head>
<body>

<div class="container">
	
	<header>
		<div class="header-left"><span>Cool</span>Logo</div>
		<div class="header-center">
			<ul>
				<li><a href="#">Our products</a></li>
				<li><a href="#">Pricing</a></li>
				<li><a href="#">Blog</a></li>
			</ul>
		</div>
		<div class="header-right"><button>Buy now</button></div>
	</header>

	<section class="main-content">
		<h2>Header with three justify aligned sections</h2>
		<p>Using the power of flexbox, the logo, links, and button of our header stay in their designated places, no matter the screen size. The <strong style="white-space: nowrap;">justify-content</strong> property offers a clean approach and allows us to align the section of the header without a hassle. No need for any floats, margins or crazy width calculations.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
		<div class="placeholder"></div>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
	</section>

</div>

</body>
</html>

Full responsiveness

The space-between trick will always take care of the alignment, even when the screen size changes. However, when the viewport becomes too small for a horizontal header, we can make it go vertical by changing the flex-direction property in a media query.

@media (max-width: 1000px){
	header{
		/* Reverse the axis of the header, making it vertical. */
		flex-direction: column;
		
		/* Align items to the begining (the left) of the header. */
		align-items: flex-start;
	}
}

Conclusion

This sums up our quick tutorial! We hope you found it useful and will start applying it right away. Flexbox has pretty good browser support nowadays, so unless your user base is IE heavy, this technique can be applied without causing any mayhem.

To learn more about flexbox and the CSS properties that we used, check out these links:

Learn Sass In 15 Minutes

learn-sass-in-15-minutes

If you write copious amounts of CSS, a pre-processor can greatly decrease your stress levels and save you a lot of precious time. Using tools such as SassLessStylus or PostCSS makes large and complicated stylesheets clearer to understand and easier to maintain. Thanks to features like variables, functions and mixins the code becomes more organized, allowing developers to work quicker and make less mistakes.

We’ve worked with pre-processors before as you may remember from our article about Less. This time we are going to explain Sass and show you some of it’s main features.

1. Getting Started

Sass files cannot be interpreted by the browser, so they need compiling to standard CSS before they are ready to hit the web. That’s why you need some sort of tool to help you translate .scss files into .css. Here you have a couple of options:

  • The simplest solution is a browser tool for writing and compiling Sass right on the spot – SassMeister.
  • Use a 3rd party desktop app. Both free and paid versions are available. You can go here to find out more.
  • If you are a CLI person like we are, you can install Sass on your computer and compile files manually.

If you decide to go with the command line, you can install Sass in it’s original form (written in ruby) or you can try the Node.js port (our choice). There are many other wrappers as well, but since we love Node.js we are going to go with that.

Here is how you can compile .scss files using the node CLI:

node-sass input.scss output.css

Also, here is the time to mention that Sass offers two distinct syntaxes – Sass and SCSS. They both do the same things, just are written in different ways. SCSS is the newer one and is generally considered better, so we are going to go with that. If you want more information on the difference between the two, check out this great article.

2. Variables

Variables in Sass work in a similar fashion to the those in any programming language, including principals such as data types and scope. When defining a variable we store inside it a certain value, which usually is something that will often reoccur in the CSS like a palette color, a font stack or the whole specs for a cool box-shadow.

Below you can see a simple example. Switch between the tabs to see the SCSS code and it’s CSS translation.

$title-font: normal 24px/1.5 'Open Sans', sans-serif;
$cool-red: #F44336;
$box-shadow-bottom-only: 0 2px 1px 0 rgba(0, 0, 0, 0.2);

h1.title {
  font: $title-font;
  color: $cool-red;
}

div.container {
  color: $cool-red;
  background: #fff;
  width: 100%;
  box-shadow: $box-shadow-bottom-only;
}
h1.title {
  font: normal 24px/1.5 "Open Sans", sans-serif;
  color: #F44336; 
}

div.container {
  color: #F44336;
  background: #fff;
  width: 100%;
  box-shadow: 0 2px 1px 0 rgba(0, 0, 0, 0.2);
}


The idea behind all this is that we can later on reuse the same values more quickly, or if a change is needed, we can provide the new value in just one place (the definition of the variable), instead of applying it manually everywhere we’re using that property.

3. Mixins

You can think of mixins as a simplified version of constructor classes in programming languages – you can grab a whole group of CSS declarations and re-use it wherever you want to give and element a specific set of styles.

Mixins can even accept arguments with the option to set default values. In the below example we define a square mixin, and then use it to create squares of varying sizes and colors.

@mixin square($size, $color) {
  width: $size;
  height: $size;
  background-color: $color;
}

.small-blue-square {
  @include square(20px, rgb(0,0,255));
}

.big-red-square {
  @include square(300px, rgb(255,0,0));
}
.small-blue-square {
  width: 20px;
  height: 20px;
  background-color: blue; 
}

.big-red-square {
  width: 300px;
  height: 300px;
  background-color: red;
}

Another efficient way to use mixins is when a property requires prefixes to work in all browsers.

@mixin transform-tilt() {
  $tilt: rotate(15deg);

  -webkit-transform: $tilt; /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 */
      -ms-transform: $tilt; /* IE 9 */
          transform: $tilt; /* IE 10, Fx 16+, Op 12.1+ */
}

.frame:hover { 
  @include transform-tilt; 
}
.frame:hover {
  -webkit-transform: rotate(15deg);  /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 */
  -ms-transform: rotate(15deg);  /* IE 9 */
  transform: rotate(15deg);  /* IE 10, Fx 16+, Op 12.1+ */ 
}

4. Extend

The next feature we will look at is @extend, which allows you to inherit the CSS properties of one selector to another. This works similarly to the mixins system, but is preferred when we want to create a logical connection between the elements on a page.

Extending should be used when we need similarly styled elements, which still differ in some detail. For example, let’s make two dialog buttons – one for agreeing and one for canceling the dialog.

.dialog-button {
  box-sizing: border-box;
  color: #ffffff;
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
  padding: 12px 40px;
  cursor: pointer;
}

.confirm {
  @extend .dialog-button;
  background-color: #87bae1;
  float: left;
}

.cancel {
  @extend .dialog-button;
  background-color: #e4749e;
  float: right;
}
.dialog-button, .confirm, .cancel {
  box-sizing: border-box;
  color: #ffffff;
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
  padding: 12px 40px;
  cursor: pointer; 
}

.confirm {
  background-color: #87bae1;
  float: left; 
}

.cancel {
  background-color: #e4749e;
  float: right; 
}

If you check out the CSS version of the code, you will see that Sass combined the selectors instead of repeating the same declarations over and over, saving us precious memory.

5. Nesting

HTML follows a strict nesting structure whereas in CSS it’s usually total chaos. With Sass nesting you can organize your stylesheet in a way that resembles the HTML more closely, thus reducing the chance of CSS conflicts.

For a quick example, lets style a list containing a number of links:

ul {
  list-style: none;

  li {
    padding: 15px;
    display: inline-block;

    a {
      text-decoration: none;
      font-size: 16px;
      color: #444;
    }

  }

}
ul {
  list-style: none; 
}

ul li {
  padding: 15px;
  display: inline-block; 
}

ul li a {
  text-decoration: none;
  font-size: 16px;
  color: #444; 
}

Very neat and conflict proof.

6.Operations

With Sass you can do basic mathematical operation right in the stylesheet and it is as simple as applying the appropriate arithmetic symbol.

$width: 800px;

.container { 
  width: $width;
}

.column-half {
  width: $width / 2;
}

.column-fifth {
  width: $width / 5;
}
.container {
  width: 800px; 
}

.column-half {
  width: 400px; 
}

.column-fifth {
  width: 160px; 
}

Although vanilla CSS now also offers this feature in the form of calc(), the Sass alternative is quicker to write, has the modulo % operation, and can be applied to a wider range of data-types (e.g. colors and strings).

7. Functions

Sass offers a long list of built-in functions. They serve all kinds of purposes including string manipulation, color related operations, and some handy math methods such as random() and round().

To exhibit one of the more simple Sass functions, we will create a quick snippet that utilizes darken($color, $amount) to make an on-hover effect.

$awesome-blue: #2196F3;

a {
  padding: 10 15px;
  background-color: $awesome-blue;
}

a:hover {
  background-color: darken($awesome-blue,10%);
}
a {
  padding: 10 15px;
  background-color: #2196F3; 
}

a:hover {
  background-color: #0c7cd5; 
}

Except the huge list of available functions, there is also the options to define your own. Sass supports flow control as well, so if you want to, you can create quite complex behaviors.

Conclusion

Some of the above features are coming to standard CSS in the future, but they are not quite here yet. In the meantime, pre-processors are a great way improve the CSS writing experience and Sass is a solid option when choosing one.

We only covered the surface here, but there is a lot more to Sass than this. If you want to get more familiar with everything it has to offer, follow these links:

Creating Your First Desktop App With HTML, JS and Electron

creating-your-first-desktop-app-with-electron

Web applications become more and more powerful every year, but there is still room for desktop apps with full access to the hardware of your computer. Today you can create desktop apps using the already familiar HTML, JS and Node.js, then package it into an executable file and distribute it accordingly across Windows, OS X and Linux.

There are two popular open source projects which make this possible. These are NW.js, which we covered a few months ago, and the newer Electron, which we are going to use today (see the differences between them here). We are going to rewrite the older NW.js version to use Electron, so you can easily compare them.

Getting Started With Electron

Apps built with Electron are just web sites which are opened in an embedded Chromium web browser. In addition to the regular HTML5 APIs, these websites can use the full suite of Node.js modules and special Electron modules which give access to the operating system.

For the sake of this tutorial, we will be building a simple app that fetches the most recent Tutorialzine articles via our RSS feed and displays them in a cool looking carousel. All the files needed for the app to work are available in an archive which you can get from the Download button near the top of the page.

Extract its contents in a directory of your choice. Judging by the file structure, you would never guess this is a desktop application and not just a simple website.

Directory Structure

Directory Structure

We will take a closer look at the more interesting files and how it all works in a minute, but first, let’s take the app for a spin.

Running the App

Since an Electron app is just a fancy Node.js app, you will need to have npm installed. You can learn how to do it here, it’s pretty straightforward.

Once you’ve got that covered, open a new cmd or terminal in the directory with the extracted files and run this command:

npm install

This will create a node_modules folder containing all the Node.js dependencies required for the app to work. Everything should be good to go now, in the same terminal as before enter the following:

npm start

The app should open up in it’s own window. Notice it has a top menu bar and everything!

Electron App In Action

Electron App In Action

You’ve probably noticed that starting the app isn’t too user friendly. However, this is just the developer’s way of running an Electron app. When packaged for the public, the it will be installed like a normal program and opened like one, just by double clicking on its icon.

How it’s made

Here, we will talk about the most essential files in any electron app. Let’s start with package.json, which holds various information about the project, such as the version, npm dependencies and other important settings.

package.json

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "pretty-bytes": "^2.0.1"
  },
  "devDependencies": {
    "electron-prebuilt": "^0.35.2"
  },
  "scripts": {
    "start": "electron main.js"
  },
  "author": "",
  "license": "ISC"
}

If you’ve worked with node.js before, you already know how this works. The most significant thing to note here is the scripts property, where we’ve defined the npm start command, allowing us to run the app like we did earlier. When we call it, we ask electron to run the main.js file. This JS file contains a short script that opens the app window, and defines some options and event handlers.

main.js

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform != 'darwin') {
        app.quit();
    }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 900, height: 600});

    // and load the index.html of the app.
    mainWindow.loadURL('file://' + __dirname + '/index.html');

    // Emitted when the window is closed.
    mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
});

Take a look at what we do in the ‘ready’ method. First we define a browser window and set it’s initial size. Then, we load the index.html file in it, which works similarly to opening a HTML file in your browser.

As you will see, the HTML file itself is nothing special – a container for the carousel and a paragraph were CPU and RAM stats are displayed.

index.html

<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Tutorialzine Electron Experiment</title>

    <link rel="stylesheet" href="./css/jquery.flipster.min.css">
    <link rel="stylesheet" href="./css/styles.css">

</head>
<body>

<div class="flipster">
    <ul>
    </ul>
</div>

<p class="stats"></p>

<!-->In Electron, this is the correct way to include jQuery<-->
<script>window.$ = window.jQuery = require('./js/jquery.min.js');</script>
<script src="./js/jquery.flipster.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>

The HTML also links to the needed stylesheets, JS libraries and scripts. Notice that jQuery is included in a weird way. See this issue for more information about that.

Finally, here is the actual JavaScript for the app. In it we access Tutorialzine’s RSS feed, fetch recent articles and display them. If we try to do this in a browser environment, it won’t work, because the RSS feed is located on a different domain and fetching from it is forbidden. In Electron, however, this limitation doesn’t apply and we can simply get the needed information with an AJAX request.

$(function(){

    // Display some statistics about this computer, using node's os module.

    var os = require('os');
    var prettyBytes = require('pretty-bytes');

    $('.stats').append('Number of cpu cores: <span>' + os.cpus().length + '</span>');
    $('.stats').append('Free memory: <span>' + prettyBytes(os.freemem())+ '</span>');

    // Electron's UI library. We will need it for later.

    var shell = require('shell');


    // Fetch the recent posts on Tutorialzine.

    var ul = $('.flipster ul');

    // The same-origin security policy doesn't apply to electron, so we can
    // send ajax request to other sites. Let's fetch Tutorialzine's rss feed:

    $.get('http://feeds.feedburner.com/Tutorialzine', function(response){

        var rss = $(response);

        // Find all articles in the RSS feed:

        rss.find('item').each(function(){
            var item = $(this);

            var content = item.find('encoded').html().split('</a></div>')[0]+'</a></div>';
            var urlRegex = /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&amp;:/~+#]*[w-@?^=%&amp;/~+#])?/g;

            // Fetch the first image of the article.
            var imageSource = content.match(urlRegex)[1];


            // Create a li item for every article, and append it to the unordered list.

            var li = $('<li><img /><a target="_blank"></a></li>');

            li.find('a')
                .attr('href', item.find('link').text())
                .text(item.find("title").text());

            li.find('img').attr('src', imageSource);

            li.appendTo(ul);

        });

        // Initialize the flipster plugin.

        $('.flipster').flipster({
            style: 'carousel'
        });

        // When an article is clicked, open the page in the system default browser.
        // Otherwise it would open it in the electron window which is not what we want.

        $('.flipster').on('click', 'a', function (e) {

            e.preventDefault();

            // Open URL with default browser.

            shell.openExternal(e.target.href);

        });

    });

});

A cool thing about the above code, is that in one file we simultaneously use:

  • JavaScript libraries – jQuery and jQuery Flipster to make the carousel.
  • Electron native modules – Shell which provides APIs for desktop related tasks, in our case opening a URL in the default web browser.
  • Node.js modules – OS for accessing system memory information, Pretty Bytes for formatting.

And with this our app is ready!

Packaging and Distribution

There is one other important thing to do to make your app ready for end users. You need to package it into an executable that can be started with a double click on users’ machines. Since Electron apps can work on multiple operating systems and every OS is different, there need to be separate distributions for Windows, for OS X and for Linux. Tools such as this npm module are a good place to start – Electron Packager.

Take into consideration that the packaging takes all your assets, all the required node.js modules, plus a minified WebKit browser and places them together in a single executable file. All these things sum up and the final result is an app that is roughly 50mb in size. This is quite a lot and isn’t practical for a simple app like our example here, but this becomes irrelevant when we work with big, complex applications.

Conclusion

The only major difference with NW.js that you will see in our example is that NW.js opens an HTML page directly, whereas Electron starts up by executing a JavaScript file and you create an application window through code. Electron’s way gives you more control, as you can easily build multi-window applications and organize the communication between them.

Overall Electron is an exciting way to build desktop web applications using web technologies. Here is what you should read next:

Using Flexbox to Create a Responsive Comment Section

flexbox-responsive-comment-section

Flexbox is a powerful new way for building layouts that makes some of the most challenging aspects of web development trivial. Nearly all browsers that are used today support it, so it is a good time to see how it can fit in your typical day-to-day frontend work.

This is why in this quick tutorial we’re going to build a comment section using flexbox. We’ll take a look at some of the more interesting properties that the flexbox layout mode has to offer and show you how to take full advantage of it.

What We’re Going to Use

Flexbox consists of a number of CSS properties, some of which we are going to use today:

  • display: flex – This activates the flex layout mode and makes the element’s children follow flexbox rules.
  • justify-content – This property defines where the children of a flexbox element will align to (this is similar to text-align, read more here).
  • order – Flexbox gives us control on the exact position elements are displayed at. We use this powerful tool in our comment section to switch the text and photo around (find out more here).
  • flex-wrap – Controls the wrapping of the elements within the flex element. We use this to force the avatars to show beneath the comment text on small screens (flex-wrap on MDN).

The Layout

We want our comment section to meet the following requirements:

  • Each comment should have an avatar, name, time and comment body.
  • There should be two comment types – those written by the author (colored in blue and having the avatar on the right) and those written by everyone else.
  • The HTML markup for both types of comments has to be as similar as possible, so it is easy to generate comments through code.
  • The whole thing has to be fully responsive.
Comment Section Layout

Comment Section Layout

All of this can be made with a few lines of CSS with flexbox. Let’s move on the the code!

The HTML

Our HTML is pretty straightforward. We’ll have a list of comments with a basic form for writing new comments at the end.

<ul class="comment-section">

    <li class="comment user-comment">
        <div class="info">
            <a href="#">Anie Silverston</a>
            <span>4 hours ago</span>
        </div>
        <a class="avatar" href="#">
            <img src="images/avatar_user_1.jpg" width="35" alt="Profile Avatar" title="Anie Silverston" />
        </a>
        <p>Suspendisse gravida sem?</p>
    </li>

    <li class="comment author-comment">
        <div class="info">
            <a href="#">Jack Smith</a>
            <span>3 hours ago</span>
        </div>
        <a class="avatar" href="#">
            <img src="images/avatar_author.jpg" width="35" alt="Profile Avatar" title="Jack Smith" />
        </a>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse gravida sem sit amet molestie portitor.</p>

    </li>

    <!-- More comments -->

    <li class="write-new">

        <form action="#" method="post">
            <textarea placeholder="Write your comment here" name="comment"></textarea>
            <div>
                <img src="images/avatar_user_2.jpg" width="35" alt="Profile of Bradley Jones" title="Bradley Jones" />
                <button type="submit">Submit</button>
            </div>
        </form>

    </li>

</ul>

If you look closely at the above code, you’ll notice that apart from having different classes, the HTML for the user comments and the author comments are practically the same. All of the stylistic and layout differences between the two, will be handled solely by CSS applied to the .user-comment and .author-comment classes.

The CSS

Here we’re going to look at flexbox-related techniques we’ve used when building the layout. If you want to examine the stylesheet in full detail, download the whole CSS file from the button near the top of the article.

First off, we are going to give all comments display: flex, which will enable us to use the flexbox properties on the comments and their child elements.

.comment{
    display: flex;
}

These flex containers span the full width of our comment section and hold the user info, avatar and message. Since we want the comments written by the author to be aligned to the right, we can use the following flex property and align everything towards the end of our container.

.comment.author-comment{
    justify-content: flex-end;
}

This will leave the comments looking like this:

justify-content: flex-end

justify-content: flex-end

Now we have the author comment aligned on the right, but we also want to have the elements inside the container in reverse order, so that the message comes first, then the avatar and the info on the far right. To do this we will take advantage of the order property.

.comment.author-comment .info{
    order: 3;
}

.comment.author-comment .avatar{
    order: 2;
}

.comment.author-comment p{
    order: 1;
}

As you can see, with the help of flexbox, the whole thing couldn’t be any easier.

Reordering Elements

Reordering Elements

Our comment section looks just like we wanted it to. The only thing left to do is make sure that it looks good on smaller devices as well. Since there won’t be as much available space on a narrower screen, we’ll have to do some rearrangements to the layout and make our content more easily readable.

We set up a media query that makes the comment paragraphs expand, taking up the whole width of the container. This will lead to the avatar and user info moving to the next line, since the comments have their flex-wrap property set to wrap.

@media (max-width: 800px){
    /* Reverse the order of elements in the user comments,
    so that the avatar and info appear after the text. */
    .comment.user-comment .info{
        order: 3;
    }

    .comment.user-comment .avatar{
        order: 2;
    }

    .comment.user-comment p{
        order: 1;
    }


    /* Make the paragraph in the comments take up the whole width,
    forcing the avatar and user info to wrap to the next line*/
    .comment p{
        width: 100%;
    }


    /* Align toward the beginning of the container (to the left)
    all the elements inside the author comments. */
    .comment.author-comment{
        justify-content: flex-start;
    }
}

The difference can be spotted right away by comparing this screen capture with the one above. You can also try opening the demo and resizing your browser to watch the comment section adapt accordingly to the size of the window.

Our comment section on smaller screens

Our comment section on smaller screens

Conclusion

This sums up our tutorial. We hope that this gave you a practical example on how to use flexbox when building real layouts. If you’re curious what else is possible, here are a few great resources that you’ll like:

  • CSS-Tricks’ guide to flexbox – here.
  • An in-depth MDN article – here.
  • A website with easy flexbox solutions for classic CSS problems – here.

Quick Tip: The Simplest Way To Center Elements Vertically And Horizontally

the-simple-way-to-center

Flexbox is a relatively new addition to the CSS world and we keep finding more and more excellent applications for it. We can even solve the age-old problem with centering an element both vertically and horizontally with CSS. It is easier than you can imagine – it is only three lines of code, doesn’t require you to specify the size of the centered element and is responsive-friendly!

This technique works in all modern browsers – IE10+, Chrome, Firefox and Safari (with the -webkit- prefix). See the full compatibility table here.

(Play with our code editor on Tutorialzine.com)

The HTML

The idea, of course, revolves around flexbox. First, we create a container in which we want everything to be centered:

<div class="container">
    <!--// Any content in here will be centered.-->
    <img src="fireworks.jpg" alt="fireworks">
</div>

You can place this container div anywhere you want. In the live example above we’ve made it take up the whole width and height of the page.

The CSS

As we said earlier, we will be using only three lines of code. Here they are:

.container{
    display: flex;
    justify-content: center;
    align-items: center;
}

Every flex container has two axis for positioning elements. The main axis is declared with the flex-direction property (can be row or column, see docs). By omitting this rule, we’ve left the flex direction to its default row value.

Now all that we need to do is center both axis. It couldn’t get any simpler:

  1. Make the display type flex, so that we activate flexbox mode.
  2. justify-content defines where flex items will align according to the main axis (horizontally in our case).
  3. align-items does the same with the axis perpendicular to the main one (vertically in our case).

Now that we have set the rules for the vertical and the horizontal alignment to center, any element we add inside the container will be positioned perfectly in the middle. We don’t need to know its dimensions beforehand, the browser will do all the hard work!

Conclusion

There are lots of other techniques for centering content with CSS, but flexbox makes this a whole lot simpler and more elegant. If you wish to learn more about it, check out these resources:

  • A complete guide to flexbox – here.
  • MDN: Using CSS flexible boxes (a long read) – here.
  • Flexbox in 5 minutes – here.
Powered by Gewgley