Tag Archiv: php

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.

10 Fun Browser Games For Learning Web Development

10-fun-browser-games

Playing video games often involves solving tricky problems with logical thinking and trial-and-error strategies. Can you think of something else that requires these skills? That’s right – programming!

In this article we’ve prepared for you 10 browser games for web developers and coders, that you can use to learn more about JavaScript, CSS and HTML, or as a proving ground for your webmaster skills. Some of the games are easy, others extremely difficult, but they are all fun!


Code Combat

Although Code Combat is made for children in school, the game can still be enjoyed by adults of all ages. In it you programatically control the actions of a brave hero going through hundreds of dungeons, fighting enemies and collecting gems. Beating the whole game takes about 20+ hours and covers most programming concepts.


Hex Invaders

In this version of the classic arcade game the world is attacked by a trio of aliens, each sporting a different color. To save humanity, the player must quickly translate a RGB hex value into human colors and shoot down the invaders.


Flexbox Froggy

Puzzle game where you have to help a group of colorful frogs get to their lillypads of choice. Moving the amphibians around is done with flexbox and will truly test you layout building skills. The in-game hints will tell you which CSS properties to use in each situation, but it’s up to the player to decide what combination of values to set.


Pixactly

Pixactly has a very simple, yet challenging concept. The game gives you two random pixel values, one for the width and one for the height of a rectangle. The player then has to draw a box that is as close as possible to the given dimensions.


CSS Diner

A great game for learning CSS selectors. The player is given a table of dishes in animated and HTML form, and a certain item or items to select from the table. The different levels cover everything a web developer should know about selectors, from the very basics to ~ and :first-child.


Screeps

You can think of this game as your digital ant farm where every “ant” is programmed by the player. After setting up a colony and the behavior of your creeps, they will go about their business of exploring the endless game world, collecting resources and fighting enemies even while you are offline.


CodinGame

A huge collection of games that can all be played in JavaScript, PHP, Ruby, Go, Python, and many other programming languages. The platform includes various puzzle, multiplayer and AI based games, while the code is written in an advanced IDE with Emacs and Vim support.


Flexbox Defense

Classic tower defense game with a CSS twist – all the turrets and traps in the game are positioned using the flexible box layout. There are 12 levels with waves of enemies trying to reach your base. To complete them all you will have to apply your entire knowledge of flexbox properties.


Elevator Saga

Elevator Saga is a puzzle game in which you use JavaScript to control the elevators in a building. Hordes of people are going up and down all the time and you have to try and get them to their destinations as quickly as possible. The game tests your algorithm writing abilities as well as your knowledge of JS functions, arrays and event handlers.


Untrusted

Untrusted is a meta-JavaScript adventure game where you play the role of Dr. Eval, an @ sign that can control the world around him by changing the source code. The player is presented with the functions that initialize every level and has to alter them using the game API to create and escape route for Dr. Eval.


Bonus: Dungeons & Developers

A talent tree with CSS, HTML and JavaScript magic instead of fire and ice. Add points in the skill you already know and see how close you are to becoming a true Web Development Master. Submit talent tree as CV for job applications at your own risk.

15 Interesting JavaScript and CSS Libraries for May 2016

interesting-libraries

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. This May our list includes JS libraries for better scrolling, jQuery plugins for creating modals, a web boilerplate from Google, and much more!


Hint.css

Pure CSS library for adding tooltips to HTML elements. Hint is very compact in size, while still managing to offer lots of options for customization such as different sizes, colors and animations. It doesn’t require any coding, tooltips are created and styled by just adding the right data attributes.


Turntable.js

With Turntable.js you can effortlessly create cool rotating demos for 3D objects by placing a large array of images into a on-hover slider. This enables users to quickly go through the whole set of pictures, creating a flipbook effect and showcasing a product from all sides.


Magic

Magic is an animation library made entirely out of vanilla CSS. This makes it extremely lightweight and easy to use, as well as buttery smooth. All animations are triggered through adding or removing classes, and can be customized by simply overwriting the default CSS rules.


Sausage

Sausage is a jQuery tool that follows the scrollbar and keeps track of which section in a page we are reading. This plugin can be of great help when designing a big documentation hub or an infinite scrolling website, since a vertical pagination will keep things way more organized.


Odometer

The new word I learned today is odometer – that’s what the mileage gauge in a car is called. This JavaScript library with the same name recreates that gadget and can be used to add vertical transitions between numbers. It’s lightweight, easy to implement, and sports a number of great looking themes such as slot machine and train station.


FullPage.js

These days we see more and more websites use the full screen slide effect, where one touch of the scroll wheel changes the entire page. Unless you are extremely DIY oriented, this library is the perfect tool for implementing such functionality – it’s elementary to use, has detailed docs, and offers great browser support.


Chart.js

Awesome library for creating eye-catching animated charts. For better performance, Chart.js relies on canvas elements to draw all the graphs, but doesn’t require of you to know anything about canvas to work with it. All the customization options (and there are a ton of them) are controlled through a simple JavaScript API.


Bricklayer

JavaScript library for building Pinterest-like cascading grids. Working with Bricklayer isn’t complicated at all and in no time you will have a robust, repsonsive layout. It also has no external dependencies, which makes it really easy to integrate with Angular, React, or any other big framework.


Flatmarket

Flatmarket is an open-source project that provides one of the cheapest and easiest to operate platforms for e-commerce. It consist of a static website for the customers and a Node.js server that handles all the payments. A CLI tool is available that makes setting up a store from scratch much simpler.


Modaal

Modaal is a jQuery plugin for creating modal popup windows that has accessibility as it’s top priority. It provides many features that make sure the end product is available to everybody, easily readable and optimized for screen readers. Some of the good practices used in Modaal are adding keyboard controls, including ARIA attributes and maintaining proper focus.


Web Starter Kit

Web Starter Kit is a collection of tools that will help developers quickly set up their projects. It’s designed by Google and focuses on providing a boilerplate that works equally well across different devices and browsers. Some of the libraries included in this kit are MDL, Sass, Babel, and gulp for task automation.


Flipside

This is a button that transforms into a dialog. The cool thing about it is the transition, which varies depending on which part of the button the user clicked. Flipside isn’t a proper library but we enjoyed it a lot so we decided to share it anyway. If you want to use it, the source code is available on GitHub.


Responsify.js

Responsify is a jQuery plugin that guarantees an image remains responsive and showing the right content. This is done by adding an attribute to <img> tags, where a focus area is defined. If the image has to be resized, Responsify will try and keep the focus area visible, and hide parts of the image that are less important.


Select2

Select boxes are still astronomically annoying to style across all browsers. Thankfully, there are plugins like Select2 which deal with that issue and offer painless embellishment of the select element and it’s options. This library also has useful extra features such as searching, infinite scrolling and IE8 support.


Vex

A tiny jQuery plugin for creating dialog pop-ups with a neat fake-3D animation effect. This library is only 2kb minified and gzipped so it practicly costs nothing to include in a project. It has a couple of available themes, and you can add your own customizations fairly easily as well.

5 Flexbox Techniques You Need to Know About

5-flexbox-techniques-you-need-to-know-about

Flexbox is a CSS standard optimized for designing user interfaces. Using the various flexbox properties we can construct our page out of small building blocks, which then are effortlessly positioned and resized any way we want. Websites and apps made this way are responsive and adapt well to all screen sizes.

In this article we’re going to take a look at five flexbox approaches to solving common CSS layout problems. We’ve also included practical examples to showcase real life scenarios in which these techniques are applied.

1. Creating Equal Height Columns

This may not seem like a difficult task at first, but making columns that have the same height can be really annoying. Simply setting min-height won’t work, because once the amount of content in the columns starts to differ, some of them will grow and others will remain shorter.

Fixing this issue using flexbox couldn’t be easier, as columns created this way have equal heights by default. All we have to do is initialize the flex model, then make sure the flex-direction and align-items properties have their default values.

.container {
        /* Initialize the flex model */
	display: flex;

        /* These are the default values but you can set them anyway */
	flex-direction: row;    /* Items inside the container will be positioned horizontally */
        align-items: stretch;   /* Items inside the container will take up it's entire height */
}
<div class="container">

	<!-- Equal height columns -->

	<div>...</div>
	<div>...</div>
	<div>...</div>
	
</div>

To see a demo of this technique, you can head out to our Easiest Way To Create Equal Height Sidebars article, in which we create a responsive page with a sidebar and main content section.

Equal Height Sidebar with Flexbox

Equal Height Sidebar with Flexbox

2. Reordering Elements

A while ago, if we had to dynamically change the order of some elements, we would probably try some CSS hack, quit in frustration, and go do it with JavaScript. With flexbox however, this task comes down to applying a single CSS property.

It’s called order and just like its name everything about it as straightforward as possible. It allows us to swap any number of flex items and change the sequence in which they appear on the screen. It’s only parameter is an integer determining the position of that element – lower numbers mean bigger priority.

.container{
	display: flex;
}

/* Reverse the order of elements */

.blue{
	order: 3;
}

.red{
	order: 2;
}

.green{
	order: 1;
}
<div class="container">

	<!-- These items will appear in reverse order -->

	<div class="blue">...</div>
	<div class="red">...</div>
	<div class="green">...</div>

</div>

The order property has many practical uses. If you want to see some of them, you can check out this article, where we use it to build a responsive comment section.

Responsive Comment Section With Flexbox

Responsive Comment Section With Flexbox

3. Horizontal And Vertical Centering

Vertical centering in CSS is one of those problems that makes us ask ourselves: How is such a trivial thing still so complicated to do? And it really is. If you google vertical centering CSS, an infinite amount of different techniques will pop up, and most of them will involve tables or transforms – things that aren’t designed for making layouts.

Flexbox offers an easier solution to the problem. Every flex layout has two directions (X axis and Y axis) and two separate properties for their alignment. By centering both we can position any element right in the middle of its parent container.

.container{
	display: flex;

	/* Center according to the main axis */
	justify-content: center;

	/* Center according to the secondary axis */
        align-items: center;
}
<div class="container">

	<!-- Any element placed here will be centered
		 both horizonally and vertically -->

	<div>...</div>

</div>

To see this tecnhique in action and read more about it, you can go to our quick-tip article on the same topic.

Horizontal And Vertical Centering With Flexbox

Horizontal And Vertical Centering With Flexbox

4. Creating Fully Responsive Grids

Most developers rely on a CSS frameworks when creating responsive grids. Bootstrap is the most popular one but there are hundreds of libraries that can help you with this task. They usually work well and have tons of options, but tend to be quite heavy. If you are a DIY person or don’t want to implement a whole framework just for the grid, flexbox has you covered!

A row in the flexbox grid is simply a container with display:flex. The horizontal columns inside it can be any amount of elements, setting the size of which is done via flex. The flex model adapts to the viewport size, so this setup should look fine on all devices. However, if we decide there isn’t enough space horizontally on the screen, we can easily turn the layout into a vertical one with a media-query.

.container{
	display: flex;
}

/* Classes for each column size. */

.col-1{
	flex: 1;
}

.col-2{
	flex: 2;
}

@media (max-width: 800px){
	.container{
		/* Turn the horizontal layout into a vertical one. */
		flex-direction: column;		
	}
}
<div class="container">

	<!-- This column will be 25% wide -->
	<div class="col-1">...</div>

	<!-- This column will be 50% wide -->
	<div class="col-2">...</div>

	<!-- This column will be 25% wide -->
	<div class="col-1">...</div>

</div>

You can check out a variation of this technique in our The Easiest Way To Make Responsive Headers Quick Tip.

flexbox-header-screen

Responsive Header With Flexbox

5. Creating The Perfect Sticky Footer

Flexbox has an easy solution to that problem as well. When building pages that include a sticky footer, by doing the whole thing in flex elements we can be sure that our footer will always stay at the bottom of the page.

Applying display: flex to the body tag allows us to construct our entire page layout using flex mode properties. Once that’s done the main content of the website can be one flex item and the footer another, which makes it really easy to manipulate their positioning and place them exactly where we want.

html{
    height: 100%;
}

body{
    display: flex;
    flex-direction: column;
    height: 100%;
}

.main{
   /* The main section will take up all the available free space
      on the page that is not taken up by the footer. */
   flex: 1 0 auto;
}

footer{
   /* The footer will take up as much vertical space as it needs and not a pixel more. */
   flex: 0 0 auto;
}
<body>
	
	<!-- All the page content goes here  -->

	<div class="main">...</div>


	<!-- Our sticky foooter -->

	<footer>...</footer>

</body>

You can find more information about this technique in our article The Best Way To Make Sticky Footers.

Sticky Footers With Flexbox

Sticky Footers With Flexbox

Conclusion

All mainstream browsers (except IE 9) now support the flex layout mode, so unless you have a user base that prefers retro Microsoft browsers, it’s safe to say that flexbox is production ready. If you haven’t used it by now, we highly recommend that you try it!

We hope you found our CSS tips useful and that they will help you build better and more robust responsive layouts. Enjoy!

Powered by Gewgley