Tag Archiv: learn

Freebie: 5 Fantastic Bootstrap Footers

5-freebie-fantastic-footers

Last time we shared with you a collection of 5 Free Bootstrap 3 Headers that can be used to kick-start any new project. Today we’ve got for you more awesome freebies and this time they are 5 ready-to-use footers templates. Just like all of our freebies, these footer designs are fully responsive, easy to implement, and 100% free to use.

The Footers

All of the footers are created using the Bootstrap 3 library. They are responsive and should look nice on any device and resolution. Each example has its own CSS file, making it very easy to customize and use. The CSS is self-contained and won’t be breaking the styles for the rest of your page.

Footer With Button

Footer With Button

How to use

To use any of the templates from the demo, follow these simple steps:

  1. Grab the zip archive from the Download button near the top of the page and extract it.
  2. Open the .html file for the template you want, copy the code inside and paste it in your project.
  3. The styles are located in separate CSS files for each design. You can find them in the /assets/css/ folder. (In the beginning of each file there are styles needed for positioning the demos, you can remove those if you want.)

The only external libraries we’ve used (apart from Bootstrap) are Font Awesome for icons, and on one of the examples an embedded map from Google Maps.

Footer With Map

Footer With Map

If you want to use the Footer With Map template you will need to generate your unique Google API key. To do so, go to the Google API console and grab a Google Maps Embed key. The whole process shouldn’t take more that a couple of minutes.

Free for Commercial Use

You have all rights to customize and use these templates. They are 100% free and can be implemented in both personal and commercial projects, no attribution required (our license page). Enjoy!

15 Awesome Sublime Text Plugins For Web Development

15-awesome-sublime-text-plugins

Sublime Text is one of the most popular code editors available right now. It is adored by many programmers for it’s speed, simplicity, and rich plugin ecosystem.

To help developers get the most our of Sublime, we decided to make a list containing some of the extensions that we use and love. If we haven’t included some of your favorites, feel free to share them with us in the comment section :)


Package Control

We cannot start off our list without mentioning Package Control. It’s the plugin manager for Sublime, and without it installing and removing packages would be a huge pain. If you do not have Package Control installed, make sure you do that first, as it will allow you to quickly try out the other plugins in this article.


JavaScript & NodeJS Snippets

A collection of shorthand snippets for writing common JavaScript expressions much faster. Why write document.querySelector('selector'); when you can simply type qs, press tab, and let Sublime do the rest of the work.


Emmet

Like the previous plugin in the list, this one let’s you use snippets to write code faster. The difference here is that instead of JS expresions, Emmet works for HTML and CSS, letting you write long tags, nested elements, or whole page templates in one go.

Emmet is a bit complex, so if want a simpler alternative you could try a similar plugin called HTML Snippets. It has less features, but is way easier to use, and has a great straightforward documentation.


Advanced New File

This awesome package makes it possible to create new files blazingly fast. Instead of browsing folders, and using the menus, you simply open a prompt with super+alt+n and write the path to your new file. The plugin will also add any non-existing directories from the path, and even supports auto completion for folder names.


Git

A Git integration that works directly from the Sublime Text command palette. The package provides quick access to a number of commonly used Git commands, allowing developers to add files, make commits, or open the Git logs, without ever leaving Sublime.


GitGutter

Very useful extension that marks each line in your source code, telling you its Git status and giving you an overview of the changes that have occurred. GitGutter can be used to compare your files to the git HEAD, origin, a branch of your choice, or even certain commits.


Side Bar Enhancements

In Sublime Text the project you are working on is overviewed in the left side panel. Although it gives you some options for working with your files, the available default actions are quite limited. This plugin changes that by adding over 20 options to the right-click menu, including Open in browser, duplicate, and lots of other useful stuff.


ColorPicker

A tiny, useful color picker that is very simple to use and great for quickly grabbing color hex values. The plugin opens in a separate window and allows you to choose a color from a palette or use an eye dropper to extract color from anywhere on your screen.


Placeholders

Sublime Text 3 has a built-in Lorem Ipsum generator that you can use for creating dummy text. The Placeholders plugin extends that functionality and allows ST to quickly generate for you placeholder images, forms, lists, and tables.


DocBlockr

This is an extension for those of you who like to add detailed comments to function definitions. DocBlockr allows you to effortlessly generate descriptions for your functions including the parameters they take, the returned value, and variable types.


SublimeCodeIntel

Code intelligence plugin that indexes your source files and enables you to find function definitions and jump to them. This extension works for a plethora of popular and not-so-popular programming languages.


Minify

A code minifer and beautifier in one. Minify takes your current opened file, and creates a new .min or .pretty version of it in the same directory. Works with CSS, HTML, JavaScript, JSONs, and SVGs.

This package relies on external node.js libraries for minifying and beautifying, so you will need to install them separately:

npm install -g clean-css uglifycss js-beautify html-minifier uglify-js minjson svgo

Sublime Linter

This package enables the code editor to check for syntax errors, bad practices, or other mistakes that the developer may have made. SublimeLinter itself just acts as a base framework for linting, so you also need to install separate plugins for each language you code in.


Color Highlighter

A feature you can see in many other IDEs and text editors, but is missing from Sublime, is color previews. Using the Color Highlighter extension you can enable it in ST, allowing you to see how all hex and RGBA values are translated to color, directly in your style sheets.


Language Packs

Sublime Text has code highlighting for over 50 languages but there are some frameworks or niche web dev languages that are not supported yet. Thanks to the plugin nature of the editor, the community can create and distribute packs for any imaginable programming language:


Bonus: Themes

Installing a beautiful theme to your text editor definitely makes writing code more enjoyable. There are tons of great themes and color palletes available for Sublime text, here are a few of our favorites:

Quick Tip: Accessing The Clipboard With JavaScript

accessing-the-clipboard-with-js_

In this article we’re going to show you how to use simple vanilla JavaScript snippets to:

  1. Add text to the clipboard on user action, such as the press of a button.
  2. Modify the content of the clipboard when a user copies something.

The APIs we will be using don’t require any external libraries, and have almost perfect browser compatibility!

Copy On Click

An awesome accessibility feature you can add to your website is the ability to copy strings directly via button press. This interaction can be applied to quickly grab URLs, long strings such as SSH keys, terminal commands, hex colors, or any other data that is frequently copy & pasted.

To make this happen we will need to use a cool JavaScript method called execCommand(). It allows us to invoke a number of different events that manipulate editable content such as making text bold/italic, doing undo/redo, and also copy/cut/paste.

document.execCommand('copy');

This works exactly like pressing CTRL/Cmd+C on your keyboard, so in order to copy any text we first need to have it selected. This is possible in JavaScript thanks to the Selection API, which allows us to programatically make a text selection from any HTML element on the page.

var button = document.getElementById("copy-button"),
    contentHolder = document.getElementById("content-holder");

button.addEventListener("click", function() {

    // We will need a range object and a selection.
    var range = document.createRange(),
        selection = window.getSelection();

    // Clear selection from any previous data.
    selection.removeAllRanges();

    // Make the range select the entire content of the contentHolder paragraph.
    range.selectNodeContents(contentHolder);

    // Add that range to the selection.
    selection.addRange(range);

    // Copy the selection to clipboard.
    document.execCommand('copy');

    // Clear selection if you want to.
    selection.removeAllRanges();

}, false);

To see the example in action check out the editor below:

(Play with our code editor on Tutorialzine.com)

In the example above the content we want to copy is simply stored in a paragraph. If the text you need is not on the page, you will need to first write it in an element hidden off-screen.

Modify Copied Text

Here we will show you how to manipulate content in the clipboard after it’s been copied. This can be very useful for escaping code, formatting numbers and dates, or for other text transformations such as uppercase, lowercase, etc.

JavaScript provides us with copy() and paste() events, but they are designed in such a way that the content stored in the clipboard is secure:

  • In the copy event handler we cannot read what’s stored in clipboard, as there may be personal info which we shouldn’t have access to. We can, however, overwrite the clipboard data.
  • In the paste event it’s the opposite: we can read the data, but we cannot change it.

Since we want to read and write at the same time, we will need to use the Selection API once more. Here is the solution:

document.addEventListener('copy', function(e){

    // We need to prevent the default copy functionality,
    // otherwise it would just copy the selection as usual.
    e.preventDefault();

    // The copy event doesn't give us access to the clipboard data,
    // so we need to get the user selection via the Selection API.
    var selection = window.getSelection().toString();

    // Transform the selection in any way we want.
    // In this example we will escape HTML code.
    var escaped = escapeHTML(selection);

    // Place the transformed text in the clipboard. 
    e.clipboardData.setData('text/plain', escaped);

});

You can try the code in the editor below:

(Play with our code editor on Tutorialzine.com)

Further Reading

In this quick tip we presented you two useful snippets for working with the clipboard in pure vanilla JavaScript. We used a bunch of hip native APIs, so here they are again if you want to read more about them:

  • execCommand – Execute actions such as copy, paste, cut, bold, italic, underline, delete, and many others. – MDN, Can I Use
  • Selection API – Allows developers to make a range selection from any text on the page. – MDN, Can I Use
  • JavaScript Copy Event – An event fired when users press CTRL/Cmd+C or choose “copy” from the right-click menu. – MDN, Can I Use

Also, if you need more control over copy/paste/cut events, you can use a library such as clipobard.js. It has lots of features and provides a nice clean API for managing the clipboard.

We hope you enjoyed this article! Feel free to ask question or leave suggestions in the comment section below :)

15 Interesting JavaScript and CSS Libraries for October 2016

interesting-libraries-october-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.

Below is October’s list, packed with awesome free libraries including vanilla JS plug-ins, React components, an icon font, and much more! Enjoy :)


Leaflet

Leaflet

Leaflet is one of the most popular open-source solutions for creating interactive maps. It offers everything you’d expect out of a map library – markers, layers, zooming, and many more basic and advanced features. The project recently got it’s official 1.0 release with many improvements to the API, accessibility and performance.


Reflexbox

Reflexbox

Flexbox grid system for React that allows developers to quickly build page layouts using a simple API of 3 React components – Grid, Flex, and Box. Since it utilizes the flexbox model, all grids with Reflexbox are responsive and can be easily adjusted via the various flexbox properties.


Lory

Lory

Lightweight no-dependencies JavaScript carousel with excellent gesture controls for touch-screen devices. The library provides lots of customization options for controlling the transition speed, frequency, animations, and other details. Excellent browser-support, a clean API, and lots of examples.


Granim

Granim

Tiny, very simple to use JavaScript library for creating beautiful gradient animations. Go to the examples page to see all the features Granim provides, including linear and radial animations, image masks, and interactive change of gradient colors.


React Native Elements

React Native Elements

A UI toolkit for React Native that combines a number of useful components into one package. It includes elements such as menus, various buttons, and form inputs, with new components coming in the future. Very well documented and easy to implement.


Reframe

Reframe

JavaScript plugin that makes unresposnive elements responsive. Reframe is especially useful for <iframe> and <video> element as it preserves their original aspect ratio. Like most modern libraries, this one doesn’t rely on jQuery but can work with $('selectors') if it is included in the page.


Progress Bar

Progress Bar

Awesome library for creating responsive animated progress bars. ProgressBar.js provides a number of built in shapes, and also allows developers to create their own paths using SVG. The progress bars can be further customized through a rich JS options object.


Headroom.js

Headroom.js

Headroom is a vanilla JavaScript library that allows you to easily set up event listeners for user scroll. You can bind different functions for when the scroll moves up or down, the bottom/top of the page is reached, and other events. One of the best available solutions for creating self-toggling headers.


SpinThatSh*t

SpinThatSh*t

Sass mixins for loading indicators with fluid CSS-only animations. The spinners are extremely easy to implement as they require just one HTML element per spinner. To customize the mixins themselves you can simply change the provided SCSS variables.


Navigo

Vanilla JavaScript library that utilizes the History API to make a robust routing system with proper history on single page apps. In browsers where the History API isn’t available, Navigo automatically falls back to a hash (#) based routing.


Wysiwyg.css

Wysiwyg.css

Pretty theme for documents that have been generated from HTML or Markdown. It styles all elements on the page, providing them with proper typography, colors and paddings, greatly improving readability. Implementing the theme is as easy as adding a single class to the root element. Customization is done through Sass.


Choreographer

Choreographer

This is a library for easier handling of complex CSS animations. Choreographer makes more manageable the transition of multiple properties at once, animations that start off after different delays, and syncing with user gestures such as scrolling.


Open color

Open color

Color pallette created especially for designing user interfaces. It contains 12 colors, each having 10 variations with different intensity. Open color is available in CSS, Sass, Less, and as a plug-in for Photoshop, Illustrator, and Sketch.


Fuse.js

Fuse.js

No dependencies JavaScript library that enables you to integrate fuzzy-search (approximate string matching) to your web app. Fuse is very powerful and has lots of options for you to tinker and play with to get the exact search functionality you need.


Ionicons

Ionicons

Ionicons is the icon font from the Ionic framework, but it can be freely used as a standalone library. The collection consists of over 500 premium-quality symbols and logos, all drawn in a modern and very appealing style. One of our favorite icon fonts at the moment.

Everything You Should Know About Progressive Web Apps

progressive-web-apps_1

Progressive Web Apps is a web application which takes advantage of modern browser features and can be added to your homescreen, behaving just like a native application.

In this tutorial we’re going to show you everything you need to know about PWAs, step by step, with practical examples and a demo app. To not start from scratch, we are going to use the selfie app we made recently, and make it progressive.


What is a Progressive Web App

In its core a progressive web app isn’t any different from a normal website – it’s made of HTML, CSS and JavaScript, and lives in the browser. What separates PWAs from regular websites is a list of 10 key concepts that need to be fulfilled. Here they are, taken directly from the Google Developers website.

  1. Safe – Served via HTTPS to prevent snooping and ensure content hasn’t been tampered with.
  2. Progressive – Work for every user, regardless of browser choice because they’re built with progressive enhancement as a core tenet.
  3. Responsive – Fit any form factor: desktop, mobile, tablet, or whatever is next.
  4. Connectivity-independent – Enhanced with service workers to work offline or on low quality networks.
  5. App-like – Feel like an app to the user with app-style interactions and navigation because they’re built on the app shell model.
  6. Fresh – Always up-to-date thanks to the service worker update process.
  7. Discoverable – Are identifiable as “applications” thanks to W3C manifests and service worker registration scope allowing search engines to find them.
  8. Re-engageable – Make re-engagement easy through features like push notifications.
  9. Installable – Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.
  10. Linkable – Easily share via URL and not require complex installation.

Following these guidelines will ensure that your app works well not only when viewed in the browser, but also when started separately via a home screen shortcut. You may find the wording Google has chosen rather confusing, but don’t worry, we will explain the rules one by one later in the tutorial.


What a Progressive Web App is NOT

The concept of PWAs shouldn’t be confused with:

All of the aforementioned technologies wrap HTML apps and package them into executable files, be it an .apk, .exe or anything else, which then have to be downloaded from the respective app store and installed on the user’s device.

PWAs don’t require installation and aren’t available (yet) in Google Play or the iTunes App store. To download a PWA you need to simply visit it’s website and then save it to the home screen as a shortcut. Developing and maintaining separate iOS and Android versions is no longer an issue, but browser support needs to be taken into consideration.


1_safe1. Safe

Most progressive web apps work with native APIs and service workers, technologies that deal with sensitive data and need to be handled with caution. That’s why every PWA has to be served through a HTTPS connection.

If you don’t have access to a server with a SSL certificate, the easiest way run projects in a secure environment is via GitHub Pages or a similar service. Any GitHub repository can be hosted directly over HTTPS, and both GitHub and GitHub Pages are free for public repos.

This is where we’ve chosen to host our demo: https://tutorialzine.github.io/pwa-photobooth/.

For simple testing on a local server, you can also try Ngrok. Its a tiny tool that allows you to tunnel any currently running localhost to a secure public URL. Ngrok is free and available for Windows, Mac, and Linux.


2_progressive

2. Progressive

Essentially, what this means is that PWAs should use web technologies that are widely supported and work equally well on as many browsers as possible. As we all know, in the world of web development this is close to impossible, but still there are things we can do to cover a larger user base.

For example, in our PhotoBooth app we use the getUserMedia() API for accessing the hardware camera on a device. Its support in different browsers is quite inconsistent – Safari doesn’t support it at all, the browsers that do support it need prefixes and differ in usage.

To ensure more people can actually use our app, we cover all the prefixes:

navigator.getMedia = ( 
    navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia
);

We also show an error if none of the prefixes work:

if (!navigator.getMedia) {
    displayErrorMessage("Your browser doesn't have support for the navigator.getUserMedia interface.");
}
else {
    // Use Camera API
}

Fallbacks and polyfills should be provided where possible. The same principles go for the CSS and HTML code.


3_responsive

3. Responsive

The app should look nice on all devices, no matter their screen size. Our app has a fairly simple UI so we’ve used only a couple of media queries to control font-size, paddings, margins, etc.

Don’t be afraid to use CSS libraries and frameworks such as Bootstrap, as they make it really easy to form grids, and deal with typography and general responsiveness.


4_offline

4. Connectivity independent

This is an important one. Using service workers allows your app to work even when there is no internet connection available.

Some apps can be cached only partially: UI is cached and available offline, dynamic content still needs access to a server.

Others, like our PhotoBooth demo, can be cached in their entirety. All of the source code and resources will be saved locally and the app will work offline and online exactly the same way. Here is the code that makes the magic happen:

This is an oversimplified usage of Service Workers, use with caution in commercial projects.

First we need to make a service worker JavaScript file, and define the logic behind it.

sw.js

// Install the service worker.
this.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open('v1').then(function(cache) {
            // The cache will fail if any of these resources can't be saved.
            return cache.addAll([
                // Path is relative to the origin, not the app directory.
                '/pwa-photobooth/',
                '/pwa-photobooth/index.html',
                '/pwa-photobooth/assets/css/styles.css',
                '/pwa-photobooth/assets/fonts/MaterialIcons-Regular.woff2',
                '/pwa-photobooth/assets/js/script.js',
                '/pwa-photobooth/assets/icons/ic-face.png',
                '/pwa-photobooth/assets/icons/ic-face-large.png',
                '/pwa-photobooth/manifest.json'
            ])
            .then(function() {
                console.log('Success! App is available offline!');
            })
        })
    );
});


// Define what happens when a resource is requested.
// For our app we do a Cache-first approach.
self.addEventListener('fetch', function(event) {
    event.respondWith(
        // Try the cache.
        caches.match(event.request)
        .then(function(response) {
            // Fallback to network if resource not stored in cache.
            return response || fetch(event.request);
        })
    );
});

Then we need to link that service worker to our HTML.

index.html

<script>
// Register Service Worker.

if ('serviceWorker' in navigator) {
    // Path is relative to the origin, not project root.
    navigator.serviceWorker.register('/pwa-photobooth/sw.js')
    .then(function(reg) {
        console.log('Registration succeeded. Scope is ' + reg.scope);
    })
    .catch(function(error) {
        console.error('Registration failed with ' + error);
    });
}
</script>

Now all of the files in our project will be saved in the user’s browser. Any JavaScript variables and object should also be saved in the localStorage or IndexDB where possible.

Right now Service Workers are supported in Chrome, Firefox and Opera. Safari and Edge are also working towards adopting them, and we hope that in the future they will be available in every browser.


5_applike

5. App-like

When building PWAs, it’s recommended to follow a design concept called app-shell architecture. It sounds very complicated but essentially boils down to this: the app is separated into two major components: the shell and the content.

The shell contains all the static UI elements such as a header, menus, drawers, etc. When we cache an app, the shell should always be saved on the device, because we want it to be available at all times. That way when a user with no internet connection opens the app, they won’t see an empty screen or a running dinosaur – they will see the cached app interface and an appropriate error message.

Image Courtesy To developers.google.com

The content resides within the shell. It can also be cached but it isn’t necessary to do so as content is usually dynamic, changes frequently and can be different on every single page load.


6_fresh_

6. Fresh

Once cached, our PWA will always load from the local storage. However, if we change the service worker sw.js in any way, on the next page load the new version will be downloaded and installed.

this.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open('v1.0.1').then(function(cache) {
            // ...
        })
    );
});

Using service worker updates we can re-download resources, delete old cache, or completely change the service worker logic. You can learn more about the SW Update process from this Google Developers article – here.


7_discoverable_

7. Discoverable

By adding a Web Manifest to our app we can provide various information about it and change the way it is displayed on people’s devices. It allows apps to be saved to the home screen with a custom icon, to be started in a separate browser window, and a lot of other cool stuff.

The Web Manifest takes the form of a simple JSON file:

manifest.json

{
  "name": "Progressive Web App: PhotoBooth",
  "short_name": "PhotoBooth",
  "description": "Simple Progressive Web App for taking selfies.",
  "icons": [{
      "src": "assets/icons/ic-face.png",
      "type": "image/png",
      "sizes": "72x72"
    }, {
      "src": "assets/icons/ic-face-large.png",
      "type": "image/png",
      "sizes": "144x144 256x256" 
    }],
  "start_url": "index.html",
  "display": "standalone",
  "background_color": "#fff",
  "theme_color": "#fff",
  "orientation": "portrait"
}

Most of the properties are self explanatory so we will cover only the more important ones. To see the full Web manifest format and all the available fields go here.

  • Shortname – This is the name our app will have when saved to the home screen.
  • Icons – Array of icons with different resolutions.
  • Display – Defines how the app will be opened. We’ve chosen standalone so when started our photo booth will appear in a full-screen window without any browser navigation or menus. It will also be seen as a separate app in multitasking.

To register the manifest we have to link it to our HTML:

<!-- Web Manifest -->
<link rel="manifest" href="manifest.json">

Safari doesn’t support the Web Manifest standard yet but we can define app-like behavior with this Apple-specific meta tag:

<!-- Meta tag for app-like behaviour in iOS -->
<meta name=”apple-mobile-web-app-capable” content=”yes”>

8_notifications

8. Re-engageable

Push notifications aren’t limited to native apps any more. Thanks to service workers and the Push API, web applications can also send messages to the Android notification bar. Not all apps will benefit from having this feature, but when used properly notifications can really help engage users.

This topic goes beyond the scope of our tutorial, as Push Notifications are quite complicated and deserve a full lesson on their own. If you still want to implement notifications to your web app, here are some of the best learning resources available:

  • Google Developers, Push Notifications: Timely, Relevant, and Precise – here.
  • Google Developers, Push Notifications on the Open Web – here.
  • MDN, Using the Push API – here.
  • Push.js, Library that provides a cleaner API for handling push notifications – here.

9_installable_

9. Installable

By default any website can be manually saved to the home screen using the Add to Home Screen button from the Chrome browser menu. However, it might be rather difficult to make users “install” our app this way, since most people don’t know about that feature at all.

Thankfully, there is a way for your app to prompt users to save it with a simple installation pop-up. To prevent developers from abusing these pop ups, there isn’t any way to programmatically show them. Instead, they will appear on their own when an app fulfills a series of requirements:

  1. There is a valid Web Manifest.
  2. There is a valid Service Worker installed.
  3. The app is served over HTTPS.

We have all of the above covered, so when a user visits our app’s website a couple of times, they will get this prompt:

Add To Homescreen Prompt

Add To Homescreen Prompt

The entire installation process of our app is in this simple prompt. The install happens instantly, and once saved the PhotoBooth will be available to launch from a home screen icon, behaving exactly like a native app.


10_linkable_

10. Linkable

Anyone with a web browser has access to PWA apps and they can be shared simply via their URL. No third party tools are required for finding or installing them.

If an app runs in standalone mode, it’s also advisable to add in-app share buttons, since the browser address bar and menus aren’t visible.


Conclusion

Our PWA is now complete. We can test how well it follows the PWA rules with an official Google-made tool called Lighthouse. It recreates possible scenarios and tests the app thoroughly. Here is what it tells us about the PhotoBooth:

Lighthouse Report

Lighthouse Report

We passed!

If you want to find more PWAs to play with, go to pwa.rocks. They offer a nice collection of games and useful tools, showcasing the great power of Progressive Web Apps.

30 Learning Resources For Mastering Angular 2

30-angular-resources

Angular 2 is a vast and complex framework with a never ending learning curve. To help you grasp more of its many features, we’ve curated a list of 30 free learning resources that cover it all – from the quickstart guide to specific details and best practices.


1_official

Let’s first quickly go over the available guides and tutorials on the official Angular website. There are a bunch of different resources there and we decided it’s a good idea to explain them.

QuickStart (TypeScript version)

Angular2 apps can be written in TypeScript, Dart, or good ol’ vanilla JavaScript. There are separate versions of the official docs for each language, but the TypeScript one is by far most detailed, as this is the recommended technology to use.

This will be the starting point for most beginners to Angular2. It includes setting up a work environment and running a basic Hello World app. Don’t be fooled by its name, you will need a good hour or two to finish this QuickStart.

QuickStart (Vanilla JavaScript version)

A much simpler version of the TypeScript QuickStart. Since it is written for vanilla JavaScript this tutorial doesn’t require a complex work environment and setup, so it goes straight to the framework itself and some of it’s main concepts.

Tour of Heroes

Tour of heroes is a much more detailed tutorial than the QuickStart. It goes through the process of building a Single Page App, step by step, covering many of the must-know Angular2 features. There are TypeScript and Dart versions, but no vanilla JS.

Advanced Documentation

Here the Angular team offers over 15 standalone tutorials, each doing a very in-depth look into an important topic. You can learn about Angular animations, the lifecycle of components, the navigation router, and many other core features.

Cookbook

A collection of code snippets and quick solutions to common challenges. Here you can find a chart of the differences between Angular 1 and 2, a FAQ section on NgModules, and solutions for form validation among other helpful tips and guides.


2_tutorials

Now let’s look at some tutorials and articles written by the community. We’ve tried to include only publications that are fairly new, making them compatible with the changes in recent versions.

Upgrading Apps To Angular 2 Using ngUpgrade

A well-written article that covers everything you need to know about upgrading old Angular 1 apps to the new framework. In it you can see what Angular2 does better, which aspects of an app need the most radical changes, as well as practical code snippets to get the job done.

Router Introduction: Child Routes, Auxiliary Routes, Common Pitfalls

This tutorial focuses on the new 3.0 router component, and explains the whole process needed for configuring it correctly. The author has done a great job explaining what Single Page Apps are, how they work, and how to route them in a robust and secure way.

Ahead-of-Time Compilation

The new Angular2 compiler improves the performance of applications dramatically by taking full advantage of JavaScript Virtual Machines. In this blog post you can learn about Just-in-Time and Ahead-of-Time compilation, their pros and cons, and how to implement them.

Styling Angular 2 Components

A more beginner-oriented lesson looking at different techniques for adding CSS styles to components. It shows you how to use component inline styles, style urls, and template inline styles, and explains the advantages behind each one.

Web Workers In Angular 2

Web workers are great for doing asynchronous tasks that don’t block the UI JavaScript, something very important for Single Page Apps. Here you can learn how to run Angular apps or components as web workers, allowing them to function in the background, independent from the main app thread.

Angular Router: Declarative Lazy Loading

Angular apps tend to get really big, and at some point the source files become too large to be loaded at once. Lazy loading allows us to speed up application load time by splitting it into multiple bundles, and loading them on demand.

Dependency Injection In Angular 2

A deep dive into the greatly improved Angular2 dependency injection system and the different approaches behind the old and new DI. This article also has a second part, that further explains the host-child relationship and the visibility of dependencies.

How does Angular 2 Change Detection Really Work ?

The Angular2 change detection mechanism is much more transparent and easier to reason about than its equivalent in Angular 1. However, there are still situations where you need to know exactly whats going on under hood.

Building an Angular 2 Application for Production

Angular is a very powerful and complex framework, and it’s not surprising that it’s footprint is also quite large. In this blog post you can learn various techniques, such as Tree-shaking and minification, that will drastically reduce the size of your final app.

Taking Advantage Of Observables In Angular 2

Observables in Angular 2 can be used for handling asynch code as an alternative to Promises. They are a vast and complex topic, but this two-part tutorial does a great job of introducing them and showcasing their many use cases.

Communication Between Components & Components Design

An interesting take on design patterns for building Angular components. The article goes through the components of a YouTube music player app and the relationships between them, with lots of code examples and explanations.

Optimizing NgUpgrade Bundle Sizes

NgUpgrade is meant to bridge the gap between Angular 1 and 2 by allowing code from both frameworks to co-exist in the same app. This can greatly increase the size as both versions need to be included. You can learn how to reduce that extra footprint in this quick tip.

Three Ways to Test Angular 2 Components

In this article you will learn three different techniques that you can use to thoroughly test Angular 2 components. They are isolated testing, shallow testing, and integration testing. All three have their strengths and weaknesses and are best applied in certain scenarios.

Protecting Routes Using Guards

Protecting routes is a very common task when building applications, as we want to prevent our users from accessing areas that they’re not allowed to access. Angular 2’s router provides a feature called Guards that tries to solve exactly that problem.

Debugging Angular 2 Applications

This guide gives a comprehensive overview of the various ways you can debug an Angular 2 applications using tools such as the Chrome DevTools, Angular Augury, simple JSON pipe filters, and the console itself.


3_videos

Since we know many developers prefer interactive lessons, here are a couple of places where you can find excellent code walkthroughs and general Angular talks.

Egghead.io

Egghead.io is one of the most popular and recommended sources for learning Angular. Although many of the lessons are for pro members only, there are still lots and lots of awesome free lessons you can watch.

Adventures in Angular

Adventures in Angular is a weekly podcast dedicated to the Angular framework. The panel cover a wide array of topics and it’s probably the best place to get Angular news. The archive contains over 110 episodes, each at least 30 minutes long.

Angular 2 from Scratch

Awesome one-hour-long course covering most of the basics. Although its beginner-oriented there are lots of things everyone can learn from this video in therms of project management and workflow.

Ajden Towfeek

A YouTube channel with lots of screencasts on web development and programming, with a focus on Angular 2 and its ecosystem of related technologies, tools, and languages.

Angular University

Another YouTube channel with a large collection of Angular tutorials, courses, code examples, and quick-tips.


Last but not least, here are some resources that didn’t fit any of the above categories, but can still be essential learning tools for any Angular developer.

Rangle’s Angular 2 Training Book

The only completely free book on Angular 2 that we could find. It covers the most important Angular 2 topics, from getting started with the basic toolchain, to writing applications in a scalable and maintainable manner. You can read it in the web browser or download it as an eBook (PDF, Mobi, ePub).

TypeScript in 30 Minutes

Although you can technically write Angular 2 in vanilla JavaScript or Dart, TypeScript provides by far the best experience with the framework. Using this tutorial you can get started with the language and learn most of it’s important features.

Style Guide

The offical style guide for the framework. Contains a ton of syntax and formatting recommendations, as well as general best practices. It’s very detailed and long, but knowing Angular’s enterprise nature, you’ll probably need to go through it at some point.

Built With Angular 2

Learn from other people’s experiences with the framework by checking out this large collection of open-source applications and experiments, all developed in Angular 2.

Angular 2 Final Q&A

An interview and Q&A with the creators of the framework, right after the release of Angular 2 Final. A great place to hear more about the project and its upcoming features straight from the horses mouth.

Freebie: 5 Beautiful Bootstrap Headers

5-freebie-beautiful-headers

In this post we present to you a collection of five templates for headers and navigation bars. We’ve created them using Bootstrap 3, following all the best practices for working with the framework. The templates are ready to use and easy to incorporate in any existing design.

The Headers

To help you save time, we’ve created five different designs, that you can choose from. They are simple, fully responsive and work great on mobile devices.

Blue Header

Blue Header

Our headers can be used as part of an existing design, or can be customized easily if you have experience with Bootstrap. For some of the templates, we’ve used fonts from Google Fonts, the built-in Glyphicons set, and images from Pexels.com.

Header Nightsky

Header Nightsky

How to use

To use any of the templates from the demo, follow these simple steps:

  1. Grab the zip archive from the Download button near the top of the page and extract it.
  2. Open the .html file for the template you want, copy the code inside and paste it in your project.
  3. The styles are located in separate CSS files for each design. You can find them in the /assets/css/ folder.

Free for Commercial Use

You have all rights to customize and use these templates. They are 100% free and can be implemented in both personal and commercial projects, no attribution required (our license page). Enjoy!

15 Interesting JavaScript and CSS Libraries for September 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.

The list for September 2016 contains a wide variety of different libraries including an excellent drag-and-drop file uploader, a CSS reset, a CSS minifier, background animations, and much more!


Dropzone

Dropzone

Very polished JavaScript library that can turn any HTML element into a drag and drop zone for file uploads. Features include thumbnail previews for image uploads, multiple files at once, a progress tracker, support for large files, and many others. Highly customizable, no dependencies.


ReactMdl

React-MDL

Google’s Material Design Lite (MDL) is one of the most beautiful CSS frameworks available. Combine that with Facebooks’s hugely successful React JavaScript library and the result is React-MDL, a library that offers a huge collection of React components styled in material design fashion.


Postmate

Postmate

Postmate is a wrapper of the Window.postMessage() method, allowing pages to speak to iFrames inside them. The library provides a simple promise-based API with which developers can securely access various data about the iFrame and emit events to it from the parent page.


Particles

Particles

A very lightweight and easy to use library for creating animated backgrounds. It consists of a single 2kb .js file and only one method – Particles.init({options});, taking an object with a fair amount of customizations. There are two animations available: single particles, or connected particles forming beautiful constellations.


Recharts

Recharts

Charts library built on top of React and D3. Graphs can be created via a simple XML-like syntax, with many of the important options set directly as attributes. The library also offers a rich examples catalog with more than 50 ready-to-use components, including various Line, Bar, Pie and other types of charts.


Shephard

Shepherd

Shepherd let’s you take users on a tour of your website or app. With a simple step-based API, you can move the focus successively from one section to another. The HTML element you want to emphasize on is highlight and a text bubble pops up with a title, description and dialog buttons.


Waud

Waud

Did you know that apart from the HTML <audio>> interface there is also a complex JavaScript Web Audio API, offering a ton of advanced sound manipulations. Waud works as a 2-in-1 solution, allowing you to access the JavaScrtip API where it’s available, and the HTML API as a fallback.


Grade

Grade

Grade.js takes the two most dominant colors in an image and uses them to create elegant gradients. This effect can be used to make cool image frames or set a matching background to your entire page. The library is very small and has no dependencies whatsoever.


Rainyday

Rainyday

Add calming rain animations to your web pages using this small JavaScript library. Under the hood, Rainyday uses a HTML <canvas> element and it’s API to draw a realistic glass-like surface with random raindrops trickling down.


CSSnano

Instead of simply removing whitespace when minifying style sheets, CSSnano also does several other optimizations such as merging properties into their shorthand equivalents, removing comments, shortening color values, and many many more. CSSnano is compatible with a number of platforms, including Node.js, grunt, gulp, webpack, and the Atom text editor.


Multirange

Multirange

JavaScript and CSS library for creating input sliders with two handles, allowing users to pick intervals ranging between two numbers (e.g price between 100$ and 500$). On browsers where this behavior cannot be achieved, the library automatically goes back to using two separate sliders.


Minireset

Minireset

Minireset is a very simple CSS reset library that normalizes only the most important CSS properties without any extra sugar. It resets font-sizes, margins and paddings, sets box-sizing to border-box on all elements, and a few other useful defaults. Since it’s so small, you can easily modify this library if you need to change some of the values.


Cesium

Cesium

WebGL based JavaScript library for creating high-resolution 3D globes and 2D maps. It supports different map providers, weather simulations, and a ton of other complex features. Their Demos page has a big collection of community projects showcasing what Cesium is capable of, including a 3D map of all the building in New York and projects by NASA.


In view

In-view

Library that tracks elements on the page and reacts when they are about to leave or enter the viewport. The library has no external dependencies and is really easy to use with a simple callback syntax:

inView('.someSelector')
    .on('enter', doSomething)
    .on('exit', el => {
        el.style.opacity = 0.5;
    });

Papa Parse

Papa Parse

Papa Parse is a powerful client-side CSV parser. It is full of awesome features like conversion to JSON, support for strings, local files or URls, an asynchronous mode, a quick mode, and much more. This library has no dependencies and can work equally well with vanilla JavaScript or jQuery.

20 Protips For Writing Modern CSS

20-protips-for-writing-modern-css

In this post we want to share with you a collection of 20 useful conventions and best practices that are recommend by the CSS community. Some are tailored more towards beginners, and some are a bit advanced, but we hope everyone will find a cool trick they didn’t know about. Enjoy!


1. Beware of Margin Collapse

Unlike most other properties, vertical margins collapse when they meet. What this means is that when the bottom margin of one element touches the top margin of another, only the bigger of the two survives. Here is a simple example:

(Play with our code editor on Tutorialzine.com)

Instead of 70px between the red and blue square we have only 40px, the margin of the blue square isn’t taken into consideration at all. There are ways to battle this behavior, but it’s better to just work with it and use margins only going in one direction, preferably margin-bottom.


2. Use Flexbox For Layouts

The flexbox model exists for a reason. Floats and inline-blocks work, but they are all essentially tools for styling documents, not websites. Flexbox on the other hand is specifically designed to make it easy to create any layout exactly the way it was envisioned.

The set of properties that come with the flexbox model give developers lots of flexibility (no pun intended), and once you get used to them, doing any responsive layout is a piece of cake. Browser support nowadays is almost perfect, so there shouldn’t be anything stopping you from going full flexbox.

.container {
    display: flex;
    /* Don't forget to add prefixes for Safari */
    display: -webkit-flex;
}

We’ve featured a number of tips and trick with flexbox before on Tutorialzine. You can check them out here: 5 Flexbox Techniques You Need to Know About.


3. Do a CSS Reset

Although the situation has greatly improved over the years, there is still plenty of variation in the way different browsers behave. The best way to resolve this issue is to apply a CSS reset that sets universal default values for all elements, allowing you to start working on a clean style sheet that will yield the same result everywhere.

There are libraries like normalize.css, minireset, and ress that do this very well, correcting all imaginable browser inconsistencies. If you don’t want to use a library, you can do a very basic CSS reset yourself with these styles:

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

This may seem a bit harsh, but nullifying margins and paddings actually makes laying out elements much easier as there are no default spaces between them to take into account. The box-sizing: border-box; property is another good default, which we will talk about more in our next tip.


4. Border-box for All

Most beginners don’t know about the box-sizing property but it’s actually quite important. The best way to understand what it does is to look at it’s two possible values:

  • content-box (default) – When we set a width/hight to an element, that’s just the size for it’s content. All paddings and borders are on top of that. E.g. a <div> has a width of 100 and padding of 10, our element will take up 120 pixels (100 + 2*10).
  • border-box – The padding and border are included in the width/height. A <div> with width: 100px; and box-sizing: border-box; will be 100 pixels wide no matter what paddings or borders are added.

Setting border-box to all elements makes it so much easier to style everything, since you don’t have to do math all the time.


5. Images as Background

When adding images to your design, especially if it’s going to be responsive, use a <div> tag with the background CSS property instead of <img> elements.

This may seem like more work for nothing, but it actually makes it much easier to style images properly, keeping their original size and aspect-ratio, thanks to background-sizebackground-position, and other properties.

(Play with our code editor on Tutorialzine.com)

A drawback of this technique is that the web accessibility of your page will take a slight hit, as images won’t be crawled properly by screen readers and search engines. This issue can be resolved by the awesome object-fit but it doesn’t have full browser support yet.


6. Better Table Borders

Tables in HTML are not fun. They are quirky, almost impossible to be made responsive, and overall difficult to style. For example, if you want to add simple borders to your table and its cells, you will most probably end up with this:

(Play with our code editor on Tutorialzine.com)

As you can see, there are quite a lot of repeating borders everywhere and it doesn’t look good. Here is a quick, hack-free way to remove all doubling borders: simply add border-collapse: collapse; to the table.

(Play with our code editor on Tutorialzine.com)

Much better!


7. Write Better Comments

CSS might not be a programming language but it’s code still needs to be documented. Some simple comments are all it takes to organize a style sheet and make it more accessible to your colleagues or your future self.

For larger sections of the CSS such as major components or media-queries, use a stylized comment and leave a couple of new lines after:

/*---------------
    #Header
---------------*/
header { }

header nav { }




/*---------------
    #Slideshow
---------------*/
.slideshow { }

Details in the design or less important components can be marked with a single-line comment.

/*   Footer Buttons   */
.footer button { }

.footer button:hover { }

Also, remember that CSS doesn’t have single line // comments, so when commenting something out you still need to use the /* */ syntax.

/*  Do  */
p {
    padding: 15px;
    /*border: 1px solid #222;*/
}

/*  Don't  */
p {
    padding: 15px;
    // border: 1px solid #222;  
}

8. Everyone Loves kebab-case

Class names and ids should be written with a hyphen (-) when they contain more then one word. CSS is case-insensitive so camelCase is not an option. A long time ago, underscores used to not be supported (they are now) which made dashes the default convention.

/*  Do     */
.footer-column-left { }

/*  Don't  */
.footerColumnLeft { }

.footer_column_left { }

When it comes to naming, you may also consider BEM, which follows a set of principles that add consistency and provide a component-based approach to development. You can read more about it in this excellent CSS-Tricks article.


9. Don’t Repeat Yourself

The values for most CSS properties are inherited from the element one level up in the DOM tree, hence the name Cascading Style Sheets. Let’s take the font property for example – it is almost always inherited from the parent, you don’t have to set it again separately for each and every element on the page.

Simply add the font styles that will be most prevalent in your design to the <html> or <body> element and let them trickle down. Here are some good defaults:

html {
    font: normal 16px/1.4 sans-serif;
}

Later on you can always change the styles for any given element. What we are saying is just to avoid repetition and use inheritance as much as possible.


10. CSS Animations with transform

Don’t animate elements by directly changing their width and height, or left/top/bottom/right. It’s preferred to use the transform() property as it provides smoother transitions and makes your intentions easier to understand when reading the code.

Here’s an example. We want to animate a ball and slide it out to the right. Instead of changing the value of left, it’s better to use translateX():

.ball {
    left: 50px;
    transition: 0.4s ease-out;
}

/* Not Cool*/
.ball.slide-out {
    left: 500px;
}

/* Cool*/
.ball.slide-out {
    transform: translateX(450px);
}

Transform, as well as all of its many functions (translate, rotate, scale, etc.) have almost universal browser compatibility and can be used freely.


11. Don’t DIY, Use A Library

The CSS community is enormous and there are constantly new libraries coming out. They serve all kinds of purposes, from tiny snippets to full-blown frameworks for building responsive apps. Most of them are open-source too.

Next time you are faced with a CSS problem, before you try to tackle it with all your might and hacks, check if there isn’t already a solution available on GitHub or CodePen.


12. Keep Selector Specificity Low

Not all CSS selectors are created equal. When novice developers write CSS they usually expect that selectors will always overwrite everything above them. However, this isn’t always the case, as we’ve illustrated in the following example:

(Play with our code editor on Tutorialzine.com)


We want to be able to add the .active class to any button and make it red. This won’t work here because our button has it’s background-color set with an ID selector, which has a higher selector specificity. The rule goes like this:

ID (#id) > Class (.class) > Type (e.g. header)

Specifity also stacks so a#button.active ranks higher than a#button. Using selectors with high specificity will cause you to constantly trump old selectors with even higher ones and eventually result in !important. This leads us into our next tip:


13. Don’t Use !important

Seriously, don’t. What is a quick fix now may end up causing lots of rewrites in the future. Instead, find why your CSS selector isn’t working and change it.

The only time when it’s acceptable to !important CSS rules is when you want to override inline styles from the HTML, which in itself is another bad practice to be avoided.


14. Caps Lock For Meaning, text-transform For Style

In the HTML, write upper case letters when you want to use them for their intended semantic meaning, like when you want to emphasize the importance of a word.

<h3>Employees MUST wear a helmet!</h3>

If you need to have some text in all caps for stylistic reasons, write the text normally in the HTML, and transform it to all-caps with CSS. It will look the same but your content will make more sense if taken out of context.

<div class="movie-poster">Star Wars: The Force Awakens</div>
.movie-poster {
    text-transform: uppercase;
}

The same goes for lowercasing and capitalizing strings – text-transform handles those just as well.


15. Em, Rem, and Pixel

There is a lot of debate whether people should use em, rem, or px values for setting the size of elements and text. Truth is, all three options are viable and have their pros and cons.

All developers and projects are different, so there can’t be any strict rules on when to use which. Here are, however, some tips and general good practices for each unit:

  • em – The value of 1 em is relative to the font-size of the direct parent. Often used in media-queries, em is great for responsiveness, but it can get really confusing tracing back the exchange rate of ems to pixels for each element (1.25em of 1.4em of 16px = ?).
  • rem – Relative to the font-size of the <html> element, rem makes it really easy to scale all headings and paragraphs on the page. Leaving the <html> with it’s default fontsize and setting everything else with rem is a great approach accessibility-wise.
  • px – Pixels give you the most precision but don’t offer any scaling when used in responsive designs. They are reliable, easy to understand, and present a good visual connection between value and actual result (15px is close, maybe just a pixel or two more).

Bottom line is, don’t be afraid to experiment, try them all and see what you like best. Sometimes em and rem can save you a lot of work, especially when building responsive pages.


16. Use a Preprocessor on Large Projects

You’ve heard about them – Sass, Less, PostCSS, Stylus. Preprocessors are the next step in the evolution of CSS. They provide features such as variables, CSS functions, selector nesting, and lots of other cool stuff, making CSS code easier to manage, especially in large projects.

For a quick example, here is a snippet of using CSS variables and functions directly in a style sheet with Sass:

$accent-color: #2196F3;

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

a:hover {
    background-color: darken($accent-color,10%);
}

The only real drawback of preprocessors is that they need compiling to vanilla CSS, but if you are already using a build script in your project this shouldn’t be too much of a hassle.

To learn more about preprocessors, check out our tutorials on two of the most popular systems – Sass and Less.


17. Autoprefixers For Better Compatibility

Writing browser-specific prefixes is one of the most annoying things in CSS. They aren’t consistent, you never know exactly which ones you need, and if you do the actual process of placing them in your style sheet is a boring nightmare.

Thankfully, there are tools that automatically do that for you and will even let you decide which browsers you need supported:


18. Use Minified Code In Production

To improve the page load of your websites and apps you should always use minified resources. The minified version of your code will have all whitespace and repetitions removed, reducing the total file size. Of course, this process also makes style sheets completely unreadable so always keep a .min version for production and a regular version for development.

There are many different ways to minify CSS code:

Depending on your workflow, any of the above options can be used, but it’s recommended to automate the process in one way or another.


19. Caniuse Is Your Friend

The different web browsers still have lots of compatibility inconsistencies. Use canisue or a similar service to check if what you are using is widely supported, if it needs prefixes, or if it causes any bugs in a certain platform.

Just checking caniuse isn’t enough though. You also need to do tests (either manually or through a service) as sometimes layouts break for no obvious reasons. Knowing the preferred browsers of your userbase also helps a lot, since you can see where good support is most crucial.


20. Validate

Validating CSS might not be as important as validating HTML or JavaScript code, but running your code through a CSS Linter can still be very helpful. It will tell you if you’ve made any mistakes, warn you about bad practices, and give you general tips for improving the code.

Just like minfiers and autoprefixers, there are plenty of free validators available:

Quick Tip: Working with the JavaScript Battery API

working-with-js-battery-api

In this tutorial we’re going to show you how to use the JavaScript Battery API to improve the user experience for people in desperate need of a charger. We’ll look at the Battery API itself, as well as some techniques for getting the most out of every drop of the most precious of resources!

Monitoring Battery Life

The JavaScript Battery Status API talks to the device’s hardware and gives us accurate data about the system’s charging state. It can be accessed via the promise based navigator.getBattery() interface, or directly via the navigtator.battery object, although the second option is now deprecated and overall not recommended.

Some browsers lack support for the Battery API (you guessed it, they are Safari and IE), so a quick support check can go a long way in terms of debugging:

if(navigator.getBattery){
    // Battery API available.
    // Rest of code goes here.
}
else{
    // No battery API support.
    // Handle error accordingly.
}

Once we are sure that your user can access the API, grabbing the needed information is really easy:

navigator.getBattery()
    .then(function(batteryManager) {
        
        // Get current charge in percentages.
        var level = batteryManager.level * 100;

    })
    .catch(function(e) {
        console.error(e);
    });

The getBattery() method returns a promise and resolves with a BatteryManager object containing various information about the current status of the hardware:

  • batteryManager.level – The current charge, returns a float between 0 and 1.
  • batteryManager.charging – Is the device on power supply or not, returns true/false.
  • batteryManager.chargingTime – Remaining time in seconds till completely charged.
  • batteryManager.dischargingTime – Remaining time until battery is dead.

It also provides events that can be used to monitor changes in any of the above properties.

  • BatteryManager.onlevelchange
  • BatteryManager.onchargingchange
  • BatteryManager.onchargingtimechange
  • BatteryManager.ondischargingtimechange

Combining the raw data with the event listeners, we can easily set up a watcher for low battery levels:

navigator.getBattery()
    .then(function(battery) {    
        battery.onlevelchange = function() {

            if(battery.level<30 && !battery.charging) {
                powerSavingMode = true;
            }

        }
    });

Once we know how much juice is left in the device we can adapt the app and turn on a power saving mode if its needed.

Preserving energy

The biggest battery drainer of all components is the screen. This is especially true on smartphones and tablets where often CPUs are energy preserving, while the screens have super-ultra-full-QHD resolution with the brightness of two suns.

The first and foremost thing we can do to address this issue is limit the amount of light the screen is emitting. JavaScript doesn’t have the authority to control the brightness directly, but we can do so by changing the color pallet to a darker theme.

dark-theme

Dark colors need less energy to be displayed, with more than 50% reduction on AMOLED screens.

The next thing we can do is limit the amount and size of requests to external resources. The biggest drainers here are high-res images, advertisements, and large JavaScript libraries, as they need a lot of bandwidth to download.

Here we have two options – load an alternative, more optimized resource with a smaller footprint, or, fully remove the image/advert if it doesn’t portray any essential information. Any background images, videos or animations should be removed.

removed-ads

Removing non-essential elements from the page makes the vital content easier to reach when in a hurry.

The last battery-drainer we will talk about is JavaScript. We already mentioned that download large libraries and frameworks is bad enough, but the actual parsing and execution of JS block can also lead to unnecessary spending.

JavaScript animations that cause constant redrawing of elements on the screen, listening for notifications form the server, and multiple AJAX requests can all drain the battery just a tiny bit, but it quickly adds up. According to this study, the JavaScript code consumes ~7% of Yahoo’s total rendering energy, ~17% on Amazon, and more than 20% on YouTube.

App With Powersaving Mode

We have showcased some of the above concepts in a simple demo app. It consists of a static website which reacts to the amount of battery left. When it gets below 30% the app goes into PowerSaving and turns darker, stops all animations, and removes all ads.

For demonstration purposes our app works with a virtual battery to enable quick toggling between fully charged and almost dead. It does not contain much code for working with the Battery API itself.

Our Demo App

Our Demo App

You can get the full code for the demo from the Download button near the top of the article. It’s written in Vue.js for easier data monitoring and has lots of comments to guide you through all that is happening.

Further Reading

If you want to find out more about the Battery Status API or about ways your precious battery is running down the drain, check out these excellent resources:

Battery Status API on MDN – here
The BatteryManager interface on MDN – here
5 Ways to Improve Battery Life in Your App – here
Who Killed My Battery: Analyzing Mobile Browser Energy Consumption – here

Powered by Gewgley