Tag Archiv: Tutorial

15 Interesting JavaScript and CSS Libraries for August 2016

interesting-libraries-august-2016

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.

Our libraries for August 2016 follow modern conventions and have as little dependencies as possible, modular architectures, and simple APIs to ease the headaches caused by JavaScript fatigue.


Aquarelle

Library for creating magnificent watercolor effects. You can use Aqaurelle to add a fade-in animation to images and make them look as they are being painted on by smudged drops of paint. Built on top of the 3D canvas library Three.js.


SuperEmbed.js

SuperEmbed is a no-dependencies library that detects embeded videos on the page and makes them responsive without messing up their original aspect ratio. It works with many popular media sources including YouTube, Vimeo, Twitch, Vine, and many others.


Vuikit

A Vue.js implementation of the popular UIkit front-end framework. The developers behind Vuikit have recreated most of UIkit’s components and made them work naturally with Vue and it’s data driven logic so that you can now build responsive Vue.js apps with little to no effort.


Staticman

With Staticman you can add dynamic content to your static Jekyll websites. If your site is hosted on GibHub pages you can implement a comment section or any other user content form, which when submitted will push the data from the form as a file to your repository. Staticman also gives the option to push new content to a separate branch, so that it won’t show up on the website until the pull request is approved.


Choices.js

Library for creating better form fields. It offers many improvements over the default input elements like multiple entries per field, prettier select boxes, and linked form fields. Choices is written in vanilla JavaScript in it’s entirety so it’s very lightweight.


Flatpickr

You may have heard of Flatpickr as it is one of the most widely used date and time pickers available. We are including it in our list because it’s authors have recently announced version 2.0, introducing lots of new features like jQuery compatibility, improved performance, SVG icons, and more.


Uppy

JavaScript file uploader that can fetch files from services such as Dropbox and Instagram, as well as from a local hard drive. It has support for resumable uploads and is separated into opt-in modules to keep it lightweight. Uppy is still in the early stages of development but you can already tell it’s a very promising project.


Skippr

Skippr is a jQuery slideshow plugin, and from all the jQuery slideshow plugins that we’ve seen, this one is probably the easiest one to use. Installation is simple, the requried HTML markup is clean, and the jQuery method takes a straightforward options object.


Howler.js

Modern library for working with audio in the web. Howler is modular, dependency-free, and fully supported in all mainstream browsers. It provides developers with the entire set of tools and controls needed for implementing sound into a website or app.


Overhang.js

Overhang.js adds stylish and well-animated pop-up notifications on top of any DOM element of your choice. This tiny jQuery plugin offers a number of modal types that can be easily implemented as a replacement for the default alert, prompt and confirm dialogs.


Baffle.js

Baffle is a tiny JavaScript library for concealing text from the screen. The information you want to hide can be camouflaged with rectangular blocks, random symbols, or any other strings. The library provides all the methods you may ever need as well as some animation options.


Jets

Jets is a clever library that utilizes CSS selectors to do blazing fast searches. Instead of hiding non-matching search results one-by-one with individual attributes, Jets creates a single <style> tag on the parent container with a dynamic CSS selector that filters out elements based on their content.


Intercooler.js

Intercooler.js allows developers to quickly implement AJAX directly in the HTML. By adding a specific HTML attribute to your links and buttons you can enable them to send GET, POST, or other requests to a URL. The data returned from the server can also be accessed through HTML attributes.


SecLists

A gigantic collection of sample data for security assessments. The data comes in lists calssified in various types (usernames, passwords, URLs, etc.), with each type containing dozens of lists full of dummy entries or actual common passwords and usernames that people use (e.g. 500-worst-passwords.txt or top_1000_usa_malenames_english.txt).


Jumpsuit

Efficient React/Redux framework that brings together the best standards in JavaScript development and allows you to get a head start on your apps. Jumpsuit gives you a helpful CLI that simplifies setting up all the libraries and tasks needed for working with React.

Building Your First App With Vue.js

building-your-first-app-with-vuejs

Today we’re going to exercise our Vue.js skills by building a simple app for browsing reddit posts. We’re going to construct the whole thing from scratch to demonstrate just how easy it is to create user interfaces with a framework like Vue.

This tutorial requires you to have at least some basic knowledge of JavaScript and Vue.js. If you aren’t familiar with Vue.js at all, we advise you to go and check out our article 5 Practical Examples For Learning Vue.js, where we show many of the core concepts with practical code snippets.

The App

What we want from our application is simply to fetch the feed from a number of subbreddits and display them. Here is what the end result will look like:

vue-app

Our Vue.js App

We will have six separate subreddit feeds showing five posts each. The posts have links to the content and discussion on reddit, as well as some other details. For the sake of simplicity we have omitted features such as adding/removing subreddits and doing searches, but they can be easily added on top of the existing app.

Setting Up The Workspace

You can download the full source code for the reddit browser app from the Download button near the top of the article. Before we actually look at the code, let’s make sure that everything is setup properly. Here is an overview of the file structure:

Our project's folder

Our project’s folder

As you can see it’s quite basic: we just have one HTML file, one CSS file, a script.js containing our JavaScript code. We’ve also added local copies of the Vue.js and Vue-resource libraries, but you can use a CDN if you prefer.

Thankfully, Vue.js doesn’t require any special configuration, so it should work straight out of the box. To start the app we just have to create a global Vue instance:

new Vue({
    el: 'body'
});

The only thing left to do now is start a local web server to enable cross-origin AJAX requests to the reddit API. The easiest way to do this on OS X/Ubuntu is by running the following command from the project’s directory:

python -m SimpleHTTPServer 8080

If everything is done properly our project should be available at localhost:8080.

Creating Custom Components

Our app is going to need two reusable components – one for the Posts, and another for Subreddits. The two components will be in a Child-Parent relationship, meaning that the Subreddit component will have multiple Posts nested in it.

Components Structure

Components Hierarchy

Let’s start with the Subreddit component, and more specifically it’s JavaScript:

// Parent | Subreddit component containing a list of 'post' components. 
var subreddit = Vue.component('subreddit',{
    template: '#subreddit',
    props: ['name'],

    data: function () {
        return { posts: [] }
    },

    created: function(){
        this.$http.get("https://www.reddit.com/r/"+ this.name +"/top.json?limit=5")
        .then(function(resp){
            this.posts=resp.data.data.children;
        });
    }
});

Here we define the new component under the name subreddit. In props we provide an array with all the parameters our component can receive – in this case it is just the name of the subbreddit we want to browse. Now if we want to add a subreddit block to the HTML we will use this markup:

<subreddit name="food"></subreddit>

The data property defines what variables are needed for each instance of the component and their default values. We will start with an empty posts array, and populate it in the created method. When a <subreddit> tag is created, Vue will take its name property, make a call to the reddit API to fetch the top 5 posts from the subreddit with that name, and save them in this.posts. For the HTTP requests we’ve used the vue-resource library instead of jQuery, since it is way tinier and automatically binds the correct context for this.

After we’ve acquired everything we need in the model, Vue.js will automatically render our Subreddit components. The actual view that the user sees is defined in a template in index.html:

<template id="subreddit">

    <div class="subreddit">
        <h2>{{ name | uppercase }}</h2>

        <ul class="item-list">
            <li v-for="obj in posts">
                <post :item="obj"></post>
            </li>
        </ul>
    </div>

</template>

Personally, I like to wrap all the elements of a component in a div container. This makes them easier to style and also seems more semantic (to me at least). Inside that container we have a title (the uppercase filter comes built-in with Vue) and an unordered list iterating over the elements returned from the reddit API call.

If you look closely at the HTML, you’ll also notice we are using a <post> tag. This isn’t some new fancy HTML element – it’s our child component!

// Child | Componenet represiting a single post.
var post = Vue.component('post', {
    template: "#post",
    props: ['item']
});

Post components will expect a object called item containing all of the information about a single post on reddit – things like title, URLs, number of comments, etc. As we saw earlier, this is done in a v-for loop inside the Subreddit (parent) component:

<li v-for="obj in posts">
    <post :item="obj"></post>
</li>

The colon prefixing :item="obj" is very important. It tells Vue that we are proving a JavaScript object called obj (as opposed to the string "obj"), allowing us to pass the data from the v-for.

Now that we have all the needed properties for a post, we can display them. The template looks scary at first, but really isn’t:

<template id="post">

    <div class="post">
        <a   :href="item.data.url" :style="item.data.thumbnail | setAsBackground" 
             target="_blank" class="thumbnail"></a>

        <div class="details">
            <a :href="item.data.url" :title="item.data.title" target="_blank" class="title">
                {{ item.data.title | truncate}}
            </a>          
            
            <div class="action-buttons">
                <a href="http://reddit.com{{ item.data.permalink }}" title="Vote">
                    <i class="material-icons">thumbs_up_down</i>
                    {{item.data.score}}
                </a>

                <a href="http://reddit.com{{ item.data.permalink }}" title="Go to discussion">
                    <i class="material-icons">forum</i>
                    {{item.data.num_comments}}
                </a>
            </div>
        </div>
    </div>
    
</template>

The only thing worth mentioning here is the use of the setAsBackground and truncate filters. In contrast to the uppercase filter we used earlier, they don’t come bundled with Vue and we had to make them ourselves.

Creating Custom Filters

Defining filters is quite easy. The Vue.filter() method provides us with the incoming string data, which we can transform whatever way we want and then simply return.

The first filter we’ll need takes the preview image for a post and creates a CSS rule setting it as background. We use this to set the inline styles with less effort.

It takes one parameter: the URL for the image. If that’s not available a placeholder image is shown instead.

// Filter that takes an image url and creates a CSS style.
Vue.filter('setAsBackground', function(value) {
    if(value && value!='self' && value!='nsfw') {
        return 'background-image: url(' + value + ')';  
    }
    else {
        return 'background-image: url(assets/img/placeholder.png)';   
    }
});

Our other filter takes strings and truncates them if they are too long. This is applied to the post titles, which often are way too lengthy for the design we had in mind.

// Filter for cutting off strings that are too long.
Vue.filter('truncate', function(value) {
    var length = 60;

    if(value.length <= length) {
        return value;
    }
    else {
        return value.substring(0, length) + '...';            
    }
});

The Full Code

Below we’ve listed all of the files for the app, so that you can look through the full code and get a better idea how the whole thing works.

/*-----------------
    Components 
-----------------*/

// Parent | Subreddit component containing a list of 'post' components. 
var subreddit = Vue.component('subreddit',{
    template: '#subreddit',
    props: ['name'],

    data: function () {
        return { posts: [] }
    },

    created: function(){
        this.$http.get("https://www.reddit.com/r/"+ this.name +"/top.json?limit=3")
        .then(function(resp){
            this.posts=resp.data.data.children;
        });
    }
});


// Child | Componenet represiting a single post.
var post = Vue.component('post', {
    template: "#post",
    props: ['item']
});


/*-----------------
   Custom filters 
-----------------*/

// Filter for cutting off strings that are too long.
Vue.filter('truncate', function(value) {
    var length = 60;

    if(value.length <= length) {
        return value;
    }
    else {
        return value.substring(0, length) + '...';            
    }
});


// Filter that takes an image url and creates a CSS style.
Vue.filter('setAsBackground', function(value) {
    if(value && value!='self' && value!='nsfw') {
        return 'background-image: url(' + value + ')';  
    }
    else {
        return 'background-image: url(assets/img/placeholder.png)';   
    }
});


/*-----------------
   Initialize app 
-----------------*/

new Vue({
    el: 'body'
});
<!DOCTYPE html>
<html>
<head>
    <title>Your First App With Vue.js</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="assets/css/styles.css">
</head>
<body>
    <div class="container">
        <subreddit name="aww"></subreddit>
        <subreddit name="space"></subreddit>
        <subreddit name="gifs"></subreddit>
        <subreddit name="food"></subreddit>
        <subreddit name="comics"></subreddit>
        <subreddit name="sports"></subreddit>
    </div>


    <template id="subreddit">
        <div class="subreddit">
            <h2>{{ name | uppercase }}</h2>
            <ul class="item-list">
                <li v-for="obj in posts">
                    <post :item="obj"></post>
                </li>
            </ul>
        </div>
    </template>

    <template id="post">
        <div class="post">
            <a   :href="item.data.url" :style="item.data.thumbnail | setAsBackground" 
                 target="_blank" class="thumbnail"></a>
            <div class="details">
                <a :href="item.data.url" :title="item.data.title" target="_blank" class="title">
                    {{ item.data.title | truncate}}
                </a>          
                
                <div class="action-buttons">
                    <a href="http://reddit.com{{ item.data.permalink }}" title="Vote">
                        <i class="material-icons">thumbs_up_down</i>
                        {{item.data.score}}
                    </a>

                    <a href="http://reddit.com{{ item.data.permalink }}" title="Go to discussion">
                        <i class="material-icons">forum</i>
                        {{item.data.num_comments}}
                    </a>
                </div>
            </div>
        </div>       
    </template>

    <script src="assets/js/vue.js"></script>
    <script src="assets/js/vue-resource.min.js"></script>
    <script src="assets/js/script.js"></script>
</body>
</html>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

a{
    text-decoration: none;
}

a:hover{
    text-decoration: underline;
}

html{
    font: normal 16px sans-serif;
    color: #333;
    background-color: #f9f9f9;
}

.container{
    padding: 27px 20px;
    margin: 30px auto 50px;
    max-width: 1250px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    background-color: #fff;
    box-shadow: 0 0 1px #ccc;
}

/* Subreddit component */

.subreddit{
    flex: 0 0 33%;
    min-width: 400px;
    padding: 20px 42px;
}

.subreddit h2{
    font-size: 18px;
    margin-bottom: 10px;
}

.subreddit .item-list{
    border-top: 1px solid #bec9d0;
    padding-top: 20px;
    list-style: none;
}

.subreddit .item-list li{
    margin-bottom: 17px;
}

/* Post component */

.post{
    display: flex;
}

.post .thumbnail{
    display: block;
    flex: 0 0 60px;
    height: 60px;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    margin-right: 10px;
    border-radius: 4px;
    margin-right: 12px;
}

.post .details{
    display: flex;
    flex-direction: column;
}

.post .details .title{
    font-size: 15px;
    margin-bottom: 3px;
    color: #04477b;
}

.post .details .title:visited{
    color: purple;
}

.post .details .action-buttons a{
    font-size: 11px;
    margin-right: 4px;
    display: inline-block;
    color: #666;
}

.post .details .action-buttons i{
    font-size: 10px;
    margin-right: 1px;
}

@media(max-width: 1250px){

    .container{
        justify-content: center;
        margin: 30px 30px 50px 30px;
    }
}

@media(max-width: 500px){

    .subreddit{
        min-width: 300px;
        padding: 20px 15px;
    }
}

Note that after creating our two components, the entire app interface comes down to:

<div class="container">
    <subreddit name="aww"></subreddit>
    <subreddit name="space"></subreddit>
    <subreddit name="gifs"></subreddit>
    <subreddit name="food"></subreddit>
    <subreddit name="comics"></subreddit>
    <subreddit name="sports"></subreddit>
</div>

The JavaScript file isn’t too large either and this is one of my favorite things about Vue. It does so much of the work for us that in the end we are left with a very clean and comprehensive piece of code.

Further Reading

The main focus of this tutorial was to show the process of building a simple Vue.js app. To keep it short we haven’t stopped to explain every tiny syntax peculiarity, but worry not! There are many awesome resources where you can learn the basics:

  • The official Vue.js starting guide and docs – here.
  • Excellent video series from Laracasts – here.
  • Our very own article: 5 Practical Examples For Learning Vue.js – here.

This concludes our Vue.js tutorial! We hope that you’ve had lots of fun with it and that you’ve learned a thing or two. If you have any suggestions or questions, feel free to leave a message in the comment section below :)

20 Awesome PHP Libraries For Summer 2016

20-php-libraries

Initially released in 1995, the PHP language is now of legal drinking age, but this doesn’t stop it from still being one of the most popular languages out there, and the first choice of many back-end developers.

The PHP community on GitHub is also one of the biggest and most active, with new awesome projects coming out constantly. Here are our picks for the 20 most useful and interesting open-source PHP libraries that you should check out – 2016 edition!


Monolog

With Monolog you can create advanced logging systems by sending your PHP logs to files, sockets, databases, inboxes or other web services. The library has over 50 handlers for various utilities and can be integrated into frameworks such as Laravel, Symfony2 and Slim.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

PHPExcel

A set of PHP classes that allow developers to easily implement spreadsheet editing in their apps. The library can read and write spreadsheet documents in a number of popular formats including Excel (both .xls and .xlsx), OpenDocument (.ods), and CSV to name a few.

include 'PHPExcel/IOFactory.php';

$inputFileName = './sampleData/example1.xls';

echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);

PHP-ML

An interesting library for experimenting with Machine Learning, PHP-ML gives you an easy to use API for training your bot and making it do predictions based on input data. It offers a variety of different algorithms for pattern recognition and complex statistics calculations.

use Phpml\Classification\KNearestNeighbors;

$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];

$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

$classifier->predict([3, 2]);
// returns 'b' as the [3, 2] point is closer to the points in group b

Opauth

Library for enabling users to authenticate themselves via their account in social networks or other services. Of course all the big names are available: Google, Facebook, Twitter, Github, Instagram, LinkedIn. Opauth is supported by many PHP frameworks so it can be easily integrated in most PHP apps.

'Strategy' => array(  
    // Define strategies here.

    'Facebook' => array(
        'app_id' => 'YOUR APP ID',
        'app_secret' => 'YOUR APP SECRET'
    ),
);

Whoops

Whoops greatly improves the debugging experience in PHP by displaying a detailed error page when something breaks in an app. This error page gives us the full stack trace showing the specific files and snippets of code that caused the exception, all syntax-highlighted and colorful. The Laravel framework comes with Whoops built-in.

$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$whoops->register();
// That's it!

FastCache

Implementing this caching system in your PHP apps is guaranteed to make them load way quicker by reducing the amount of queries sent to the database. Instead of executing every DB query, FastCache sends only the unique ones, saves them as cache, and then serves them from there for each repetition. This way if you have the same query repeated 1000 times, it will be loaded from the DB one time, the rest 999 loads will be from cache.

use phpFastCache\CacheManager;

$config = array(
    "storage"   =>  "files",
    "path"      =>  "/your_cache_path/dir/",
);
CacheManager::setup($config);

// Try to get from Cache first with an Identity Keyword
$products = CacheManager::get("products");

// If not available get from DB and save in Cache.
if(is_null($products)) {
    $products = "DB SELECT QUERY";
    // Cache your $products for 600 seconds.
    CacheManager::set($cache_keyword, $products,600);
}

Guzzle

Guzzle is one of the best HTTP clients out there. It can handle almost any HTTP task that you throw at it: synchronous and asynchronous requests, HTTP cookies, streaming of large uploads and downloads. Working with Guzzle is really easy and the docs are well written with lots of examples and detailed explanations.

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

Munee

Munee has lots of tricks up its sleeve: combining several CSS or JavaScript requests into one, image resizing, automatic compilation for Sass, Less and CoffeeScript files, as well as minification and Gzip compression. All of the previously mentioned processes are cached both server-side and client-side for optimal performance.

require 'vendor/autoload.php';
echo \Munee\Dispatcher::run(new \Munee\Request());
<!-- Combining two CSS files into one. -->
<link rel="stylesheet" href="/css/bootstrap.min.css, /css/demo.css">

<!-- Resizing image -->
<img src="/path/to/image.jpg?resize=width[100]height[100]exact[true]">

<!-- Files that need preprocessing are compiled automatically -->
<link rel="stylesheet" href="/css/demo.scss">

<!-- Minifying code -->
<script src="/js/script.js?minify=true"></script>

Twig

Templating engine with a very clean “mustache” syntax that makes markup shorter and easier to write. Twig offers everything you would expect from a modern templating library: variable escaping, loops, if/else blocks, as well as a secure sandbox mode for verifying template code.

// Template HTML

<p>Welcome {{ name }}!</p>


// Rendering

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
    'cache' => '/path/to/compilation_cache',
));

echo $twig->render('index.html', array('name' => 'George'));

Goutte

Goutte is a Web Scraper that can crawl websites and extract HTML or XML data from them. It works by sending a request to a given URL and returning a Crawler object, which allows the developer to interact with the remote page in various ways.

use Goutte\Client;
$client = new Client();

// Go to the symfony.com website
$crawler = $client->request('GET', 'http://www.symfony.com/blog/');

// Click on the links
$link = $crawler->selectLink('Security Advisories')->link();
$crawler = $client->click($link);

// Extract data
$crawler->filter('h2 > a')->each(function ($node) {
    print $node->text()."\n";
});

Climate

Climate is a library for people who run PHP from the command line. It offers a collection of methods for talking to the terminal (both input and output), and also some beautifying functions for coloring and formatting. It can even draw and animate cool ASCII art.

$climate = new League\CLImate\CLImate;

// Output
$climate->out('This prints to the terminal.');

// Input
$input = $climate->input('How you doin?');
$response = $input->prompt();

// Formatting
$padding = $climate->padding(10);

$padding->label('Eggs')->result('$1.99');
$padding->label('Oatmeal')->result('$4.99');
// Eggs...... $1.99
// Oatmeal... $4.99

Alice

Built on top of Faker, Alice is a library that generates fake data objects for testing. To use it you first have to define the structure of your objects and what data you want in them. Then with a simple function call Alice will transform this template into an actual object with random values.

// Template in person.yml file
Person:
    person{1..10}:
        firstName: '<firstName()>'
        lastName: '<lastName()>'
        birthDate: '<date()>'
        email: '<email()>'


// Load dummy data into an object
$person = \Nelmio\Alice\Fixtures::load('/person.yml', $objectManager);

Ratchet

The Ratchet library adds support for the WebSockets interface in apps with a PHP backend. WebSockets enable two-way communication between the server and client side in real time. For this to work in PHP, Ratchet has to start a separate PHP process that stays always running and asynchronously sends and receives messages.

class MyChat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }
}

// Run the server application through the WebSocket protocol on port 8080
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChat);
$app->run();

PHPMailer

No PHP library collection is complete without PHPMailer. This project is backed by a huge community and is implemented in popular systems such as WordPress and Drupal, making it the safest choice for sending emails in PHP. It has SMTP support, can do HTML-based emails, and much more.

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('steve@example.com');    

$mail->addAttachment('/var/tmp/file.tar.gz');        
$mail->isHTML(true);                                  

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Hoa

Hoa isn’t actually a PHP library – it’s an entire set of PHP libraries, containing all kinds of useful web development utilities. Although not all are fully documented, there are 50+ libraries right now, with new ones constantly being added. It’s completely modular so you can select only the libraries you need without any clutter.

// Hoa Mail
$message            = new Hoa\Mail\Message();
$message['From']    = 'Gordon Freeman <gordon@freeman.hf>';
$message['To']      = 'Alyx Vance <alyx@vance.hf>';
$message['Subject'] = 'Hoa is awesome!';
$message->addContent(
    new Hoa\Mail\Content\Text('Check this out: http://hoa-project.net/!')
);
$message->send();

// Hoa Session
$user = new Hoa\Session\Session('user');

if ($user->isEmpty()) {
    echo 'first time', "\n";
    $user['foo'] = time();
} else {
    echo 'other times', "\n";
    var_dump($user['foo']);
}

CssToInlineStyles

Anyone who has tried creating HTML emails knows what a pain it is to inline all of the CSS rules. This small PHP Class does the whole job for you, saving you lots of time and nerves. Just write your styles in a regular .css file and the PHP library will use the selectors to assign them at the proper tags.

use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

// create instance
$cssToInlineStyles = new CssToInlineStyles();

$html = file_get_contents(__DIR__ . '/examples/sumo/index.htm');
$css = file_get_contents(__DIR__ . '/examples/sumo/style.css');

// output
echo $cssToInlineStyles->convert(
    $html,
    $css
);

Stringy

Library for doing all kinds of string manipulations. It offers a ton of different methods for modifying text (reverse(), htmlEncode(), toAscii() etc.) or gather information about a string (isAlphanumeric(), getEncoding(), among others). A cool thing about Stringy is that it also works with special symbols like Greek or Nordic letters;

s('Camel-Case')->camelize(); // 'camelCase'

s('   Ο     συγγραφέας  ')->collapseWhitespace(); // 'Ο συγγραφέας'

s('foo & bar')->containsAll(['foo', 'bar']); // true

s('str contains foo')->containsAny(['foo', 'bar']); // true

s('fòôbàř')->endsWith('bàř', true); // true

s('fòôbàř')->getEncoding(); // 'UTF-8'

s('&amp;')->htmlDecode(); // '&'

Robo

Robo is a Gulp-like task runner, only for PHP. With it you can set up automations that improve your workflow and the time it takes to build a project after making changes. Robo can run tests, compile code from preprocessors, handle version control updates, and many other useful tasks.

// Doing a Git Commit with Robo
public function pharPublish()
{
    $this->pharBuild()->run();
    $this->_rename('robo.phar', 'robo-release.phar');
    return $this->collectionBuilder()
        ->taskGitStack()
            ->checkout('gh-pages')
        ->taskGitStack()
            ->add('robo.phar')
            ->commit('robo.phar published')
            ->push('origin', 'gh-pages')
            ->checkout('master')
            ->run();
}

PHP Humanizer

This library takes variables and transforms them into a more human-readable format using a set of methods. For example it can turn Roman numerals into numbers, truncate long strings, and calculate bytes to kB/MB/GB. Support for over 15 languages (the spoken kind, not programming ones).

use Coduo\PHPHumanizer\NumberHumanizer;

echo StringHumanizer::humanize('field_name'); // "Field Name"

echo NumberHumanizer::ordinalize(1); // "1st"
echo NumberHumanizer::ordinalize(23); // "23rd"

echo NumberHumanizer::toRoman(5); // "V"
echo NumberHumanizer::fromRoman("MMMCMXCIX"); // 3999

echo NumberHumanizer::binarySuffix(1024); // "1 kB"
echo NumberHumanizer::binarySuffix(1073741824 * 2); // "2 GB"

ColorExtractor

The last item on our list is this small library for extracting colors from images. It iterates all of the pixels in a given picture and returns a palette of the colors on it sorted by total area. Developers can then use this palette to get the most dominant colors and adapt the design according to them.

require 'vendor/autoload.php';

use League\ColorExtractor\Color;
use League\ColorExtractor\Palette;

$palette = Palette::fromFilename('./some/image.png');

$topFive = $palette->getMostUsedColors(5);
$colorCount = count($palette);
$blackCount = $palette->getColorCount(Color::fromHexToInt('#000000'));

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!

15 Interesting JavaScript and CSS Libraries for July 2016

interesting-libraries-july-2016

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.

The list for July 2016 is packed with some of the hottest open-source libraries from GitHub. It includes a touch gestures library, a powerful address picker, and loads of other useful tools!


Offline.js

Offline.js is a standalone JavaScrtip library for handling connectivity problems. It not only alerts users when they lose connection to you website, but also saves all their outgoing AJAX requests and remakes them when it is up again. The library has a slick, minimal UI with multiple themes to choose from.


Algolia Places

Algolia Places can instantly turn any input element into an address search with autocomplete. It has a built-in ranking system that suggests the most obvious choices first, and other powerful features like the ability to ignore small typos and understand what the user actually meant. It’s very easy to use and will save you a great deal of time.


Please.js

Random color generator with some cool advanced features. By default the library selects from a list of predefined colors, making sure that the outcome is always beautiful and usable. You can also make colors based on other ones, generate entire color palettes, or mess around with the saturation, hue and other options.


Holmes

JavaScript library that makes it elementary to search for and filter elements in a page. Holmes works by taking a query string from an input field and going through a list of elements looking for any matches. Elements that do not contain the query in their inner HTML are hidden, those that do are kept visible.


Monkberry

Lightweight, lightning-fast JavaScript library with its own templating engine. Monkberry templates are written in typical markup fashion in .monk files which are then compiled via JS. What makes Monkberry so swift is that when any of the input data is changed, only that part of the template is rendered instead of the entire DOM getting an update.


Zingtouch

Excellent gesture detection library that recognizes 6 different touch gestures: tap, swipe, pinch, expand, rotate, and pan. Zingtouch allows you to modify any of the predefined gestures, or make your own ones from scratch to match your exact needs.


Blaze CSS

Very flexible and pretty CSS framework for building responsive web apps. Blaze is completely modular, meaning that it allows you to pick and choose which of its many components you actually need and which ones can be left behind. It offers an advanced Bootstrap-like grid, smooth CSS transition animations, and much more.


Anime.js

Anime.js is a JavaScript animation library that’s very tiny in size yet still manages to offers a huge array of features and all the customization options you can think of. The library supports multiple technologies for doing the actual animations (CSS transforms or properties, SVG, etc.), so that developers can choose what suits their needs best.


Minigrid

Minigrid’s sole purpose is to provide an easy way for making cascading Pinterest-style grids. Users just have to write a simple HTML markup and call a short JavaScript function, the library will then create a responsive grid that will always keep itself symmetrical on any screen size by reordering its cards.


Chocolat.js

A jQuery plugin for creating beautiful lightbox image galleries. Chocolat is lightweight (only 10 kb minified), has great browser support, and a ton of features including different viewing modes and out-the-box keyboard navigation. The library also has one of the weirdest (in a cool way) and most surrealistic websites we’ve ever seen.


Stretchy

Stretchy is a no-dependency JavaScript library that allows form elements to auto-resize on user input. All text-based input fields can be made to enlarge or shorten themselves depending on the length of the string they hold. It has an easy to use API and excellent browser compatibility.


Shine.js

Shine.js creates fancy dynamic shadows that react to the position of the user’s cursor. The shadows can be applied to any HTML element including text and the effect looks stunningly realistic, as the animations are well calibrated and buttery-smooth.


BackgroundCheck

With BackgroundCheck developers can make elements on the page turn lighter or darker, adapting to the colors or images positioned in the background behind them. Any element can be targeted and will automatically change its color, showing its dark or light side and maintaining maximum visibility.


Logerr

Improve the JavaScript debugging experience with Logerr. After a very simple installation, this library will replace the default console errors with more readable and detailed messages. Another cool Logerr feature is the remote logging tool which sends POST requests containing error logs to a url of your choice.


Bigfoot

This jQuery plugin turns classic bottom-of-the-page footnotes into modern pop-up tooltips. Bigfoot offers a lot of customization options both in the styling and functionality of the footnotes. The default theme is fully responsive, changing the position and size of the tooltips to keep them visible on all screen sizes.

Freebie: Responsive Landing Page Template With Flexbox

freebie-landing-page-template

The fist impression a website leaves on potential customers often plays a huge role in their decision whether to buy or pass on a product. A landing page with a good design can keep users engaged longer and hint them that the advertised product or service is of high quality.

To help you save time on building a landing page from scratch, we created this HTML template that can be used as is or as a starting point for your start-up’s website. It’s simple, fully responsive, and 100% free!

landing-page-hero

The Design

Our template consists of a single static HTML page with several sections:

  • Header with company logo and navigation menu.
  • Hero with titles, action button and fullscreen background image.
  • Demo section with a gallery for showing off pictures or stock images.
  • Features section for listing different services or features.
  • Reviews section for quotes and recommendations.
  • Callout section with a simple input form and button.
  • Footer including social media links and text (removable).
Features And Services Section

Features And Services Section

The whole layout is responsive and looks good on all devices ranging from small phones to large desktop monitors. It doesn’t have any flashy animations or complex graphics to keep it lightweight, customizable, and lightning-fast.

The Code

The entire template is made up of just two files: a HTML layout and a CSS stylesheet. We haven’t used any frameworks, so editing and customizing it should be relatively simple. This also makes it easier if you want to implement any framework of your choice such as Bootstrap or MDL.

The only external dependencies used in the project are a couple of fonts:

For the of the CSS we’ve relied on a pretty standard set of properties, nothing too experimental. Some parts of the layout are done via flexbox, but that shouldn’t cause any compatibility issues as it has almost full browser support.

Free for Commercial Use

This landing page template is completely free and can be used in both personal and commercial projects. For more information check out Tutorialzine’s licence page.

We hope you enjoyed this template! If you want more free stuff check out our full collection of freebies and leave any suggestions for new templates that you want to see in the comments 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!

15 Interesting JavaScript and CSS Libraries for June 2016

15-interesting-libraries-june-2016

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.

For June 2016 we’ve selected for you 15 free libraries which will help you build better responsive layouts, do advanced JavaScript magic, add beauty to your projects, and much more!


Bideo.js

Use Bideo to make your landing pages cooler by adding a fullscreen video to the background. This library can be used on any HTML page, and will make sure that your video is responsive and always displayed correctly. It also offers auto play as well as showing a static cover image in case the media file takes a couple of seconds to load.


Push

Push notifications have had good browser support for a while now but have always suffered from a lack of a working cross-browser API. Push.js is a library that comes to solve this issue and offer a clean, universal way to control desktop notifications that work equally well in Chrome, Firefox, Safari and IE.


Cutestrap

Cutestrap is a CSS framework that serves as a smaller, more compact alternative to Bootstrap. In it’s 8kb the library packs a number of well-styled UI components, an advanced responsive grid, as well as a bunch of useful modifier classes. Due to it’s simplicity Cutestrap is very easy to customize via overwriting the default styles or by using Sass.


Timedropper

Timedropper is a time picker with a superb design and buttery-smooth animations. It’s built on top of jQuery and can be initialized on any input field with a simple $('#some-input').timeDropper(); call. We also highly recommend Timedropper’s brother – Datedropper, a wonderful date picker which we’ve already included in one of our previous monthly lists.


CSSgram

CSSgram is a library that offers more than 20 Instagram filters recreated using the CSS filter and blend properties. It doesn’t rely on JavaScript to achieve the desired effect, so it’s extremely simple to use – either through vanilla CSS or Sass. CSSgram works in all desktop and mobile browsers except for IE which doesn’t support CSS filters.


Flexbox Grid

Pure CSS library for creating responsive gird layouts. As the name suggests Flexbox Grid is based entirely on the flexible boxes model, which is the most modern and robust way to build layouts in HTML. Grids created using flexbox properties are very adaptive and can be aligned and positioned with little to no effort.


Intense Images

A beautiful image viewer that allows users to zoom into any media object and examine it closely in full screen. The library manages to look great without having any fancy animations or styles, which also makes it really easy to customize and tailor to your needs. Intense images has no external dependencies and should work in all modern browsers.


Picnic

Picnic is a CSS framework that differentiates itself from the huge array of front-end libraries with one unique quality – invasiveness. What this means is that Picnic CSS doesn’t rely on the user to add classes to each element for styling. Instead it invades the default styles of the page and automatically adds it’s customization to all HTML elements, leaving the markup short and clean.


Embed.js

JavaScript plugin for embedding emojis, media, maps, and all kinds of cool stuff in HTML text. When initialized on an element, Embed.js will take it’s inner text and replace specific markup in the string with special content: YouTube links turn into video, Twitter links into tweets, Spotify links into audio players, etc. A long list of services are available including Github, SoundCloud, Codepen, Instagram, and many others.


Trianglify

Trianglify is a JavaScript library for creating geometric gradient images. After setting up the dimensions of your gradient and how it should look (colors, size of cells, etc.), the end result can be drawn directly into a canvas, as an SVG DOM node, or exported as a base64 data URI. An online generator is also available.


SweetAlert2

Replace the default alert and prompt JavaScript popups with colorful, animated dialog boxes. There are five different types of messages, lots of customization options, and all the methods you’ll ever need. SweetAlert2 has great browser compatibility and as a result you’ll get popups that look the same way across all operating systems and web browsers, including IE 10+ and Edge.


Adaptive Backgrounds

This jQuery plugin analyzes images and finds out what is their most prevalent color. The primary color is then extracted and can be applied as the background of any selected HTML element. With a sprinkle of creativity this library can be used to create amazing web designs and demos.


Typed.js

With Typed.js you can replace the boring placeholders in input fields with animated ones. Just write down one or more example strings and this jQuery plugin will display them in your form as if they are being typed in. There are also some customization options such as different cursors, type speed, looping, and more.


Tabslet

A jQuery plugin for creating tabbed content, which can also be used for making carousels and paginations. Tabslet is very lightweight, but still manages to offers a ton of useful options such as animations, different event listeners, and exceptional browser compatibility with support going all the way back to for IE7.


ContentTools

ContentTools is a powerful JavaScript library that can transform any HTML page into a WYSIWYG editor. There are detailed step-by-step tutorials on the project’s website which will help you get it up and running, and once properly installed ContentTools reveals countless possibilities for building wondrous interactive apps and services.

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.
Powered by Gewgley