Monthly Archives: April 2015

Experiment: Material Design Stopwatch, Alarm and Timer

By Danny Markov

material-design-stopwatch-timer-and-alarm

We have something special for all of our readers today. We made a small JavaScript application that conforms to Google’s Material Design Guidelines. It consists of three parts – an alarm clock, a stopwatch and a timer. The application is responsive and has a bunch of subtle animations that react to user input.

Material Design Alarm Clock

What it does

You can switch (and swipe on touch devices) between three modes of operation:

  • Alarm clock – Set an alarm to go off at a specific time. This mode has an option to play alarm sounds with HTML5 audio.
  • Stopwatch – Shows elapsed time from the moment you’ve hit start. You can start, pause and reset the stopwatch.
  • Timer – Set a duration in minutes, and this mode will let you know with an alarm when the time is up.

Everything is persisted to local storage, so even if you reload the page by mistake, the app will continue working.

Note: The alarm sounds won’t work on mobile devices. That’s because, in the mobile versions of Chrome and Safari, audio can be played only in response to user action (e.g. when you tap on a button). Because we play audio after a delay, mobile browsers ignore the audio playback.

Code and Design

We use the modern Materialize framework, together with jQuery, jQuery Timepicker and Hammer.js for touch events. Materialize turns the plain looking standard HTML input fields into these awesome Android-like switches and check boxes. It also adds the the on-click wave ink effect as it has Waves.js included in it’s package.

timer1

Animations are an important part of Material Design

As for the code, we have 4 main files, which you can see in assets/js:

  • alarm.js, stopwatch.js and timer.js handle the functionality of the three clock modes. They are not dependent on each other, meaning that if you need only one of them you can use just that one without any problems.
  • script.js is for general front-end. It controls changing between the clock modes and some other minor stuff.

Hope you like it!

Go ahead and grab the zip file with the demo from the download button near the top of the article. Feel free to modify and build upon our code, and we would love it if you share the results in the comment section!

Source:: Tutorialzine.com

Making Your First Webapp with React

By Nick Anastasov

creating-your-first-web-app-with-react

React has gained a lot of popularity recently and has attracted a large and active community. This results in a vast wealth of reusable components for it that will save you time when coding. The library itself encourages writing loosely coupled code that is modular and composable.

In this tutorial, I will show you how to create a small application and how to split it into discrete components that talk to each other. As a base, we will take the npm-driven website example from last month, but we’ll do it the React way. It is interesting to compare the results – the React version has a few more lines of code than the jQuery version, but we can both agree that it is much better organized.

What you need to know about React

  • It is a popular client-side library/framework for building user interfaces, which is developed and used by Facebook.
  • With it, you organize your application around discrete components, with each handling its own rendering and state. Components can be nested within each other.
  • React is fast because it minimizes the number of writes to the DOM (the slowest part of any client-side application).
  • The recommended way to write React code is by using JSX – an extension to JavaScript which presents components as HTML elements. JSX needs to be compiled to JS in order to work in browsers.
  • It hasn’t hit version 1.0 as of this writing, so there might be changes in the future.
  • We have a nice article with examples for learning react which you can check out. Also there is the official getting started guide here.

What we will be building

We will create a simple web app, which invites people to search for locations and to store them in their browsers’ localStorage. The locations will be presented on a Google Map with the help of the GMaps plugin. We will use Bootstrap with the Flatly theme for the interface. In the process, we will break the application down into logical components and make them talk to each other.

Running the demo

If you don’t want to read the entire tutorial, you can go ahead and download the source code from the download button above. To run it, you need to have Node.js and npm installed. Assuming that you have, here is what you need to do:

  1. Download the zip with the source code from the button above.
  2. Extract it to a folder somewhere on your computer.
  3. Open a new terminal (command prompt), and navigate to that folder.
  4. Execute npm install. This will download and install all dependencies that are needed.
  5. Execute npm run build. This will compile the react components down to a regular JavaScript file named compiled.js.
  6. Open index.html in your browser. You should see the app.

There is one more npm command that I’ve prepared for you to make your development easier:

npm run watch

This will compile the JSX code down to JavaScript and will continue to monitor it for changes. If you change a file, the code will be recompiled automatically for you. You can see these commands in the package.json file.

The source code is easy to follow and has plenty of comments, so for those of you who prefer to read the source, you can skip the rest of the article.

Setting things up

As I mentioned, the recommended way to write React code is by using a JavaScript extension called JSX, which needs to be transformed to JavaScript. There are a few tools that can do this but the one I recommend is reactify – a browserify transform. So in addition to compiling JSX down to JavaScript, you get access to the require() node.js call and with it the ability to install and use libraries from npm.

To set up reactify, browserify and the rest, run this command:

npm install browserify reactify watchify uglify-js react

To create a production ready and minified JavaScript file, which you can put online, run this command in your terminal:

NODE_ENV=production browserify -t [ reactify --es6 ] main.js | uglifyjs > compiled.min.js

Reactify supports a limited set of the new ES6 features with the --es6 flag, which I’ve used in the source code (you will see it in a moment).

While developing, use the following command:

watchify -v -d -t [ reactify --es6 ] main.js -o compiled.js

Watchify will monitor your files for changes and recompile your source code if it is needed. It also enables source maps, so you can use the Chrome Debugger to step through your code.

Great! You can now write React modules, require() npm libraries and even use some ES6 features. You are ready for writing some code!

The code

Here are the components that we will be writing:

  • App is the main component. It contains methods for the actions that can be performed by the user like searching, adding a location to favorites and more. The other components are nested inside it.
  • CurrentLocation presents the currently visited address in the map. Addresses can be added or removed from favorites by clicking the star icon.
  • LocationList renders all favorite locations. It creates a LocationItem for each.
  • LocationItem is an individual location. When it is clicked, its corresponding address is searched for and highlighted in the map.
  • Map integrates with the GMaps library, and renders a map from Google Maps.
  • Search is a component that wraps around the search form. When it is submitted, a search for the location is triggered.

Components Breakdown

App.js

First up is App. In addition to the lifecycle methods that React requires, it has a few additional ones that reflect the main actions that can be performed by the user like adding and removing an address from favorites and searching. Notice that I am using the shorter ES6 syntax for defining functions in objects.

var React = require('react');

var Search = require('./Search');
var Map = require('./Map');
var CurrentLocation = require('./CurrentLocation');
var LocationList = require('./LocationList');


var App = React.createClass({

	getInitialState(){

		// Extract the favorite locations from local storage

		var favorites = [];

		if(localStorage.favorites){
			favorites = JSON.parse(localStorage.favorites);
		}

		// Nobody would get mad if we center it on Paris by default

		return {
			favorites: favorites,
			currentAddress: 'Paris, France',
			mapCoordinates: {
				lat: 48.856614,
				lng: 2.3522219
			}
		};
	},

	toggleFavorite(address){

		if(this.isAddressInFavorites(address)){
			this.removeFromFavorites(address);
		}
		else{
			this.addToFavorites(address);
		}

	},

	addToFavorites(address){

		var favorites = this.state.favorites;

		favorites.push({
			address: address,
			timestamp: Date.now()
		});

		this.setState({
			favorites: favorites
		});

		localStorage.favorites = JSON.stringify(favorites);
	},

	removeFromFavorites(address){

		var favorites = this.state.favorites;
		var index = -1;

		for(var i = 0; i < favorites.length; i++){

			if(favorites[i].address == address){
				index = i;
				break;
			}

		}

		// If it was found, remove it from the favorites array

		if(index !== -1){
			
			favorites.splice(index, 1);

			this.setState({
				favorites: favorites
			});

			localStorage.favorites = JSON.stringify(favorites);
		}

	},

	isAddressInFavorites(address){

		var favorites = this.state.favorites;

		for(var i = 0; i < favorites.length; i++){

			if(favorites[i].address == address){
				return true;
			}

		}

		return false;
	},

	searchForAddress(address){
		
		var self = this;

		// We will use GMaps' geocode functionality,
		// which is built on top of the Google Maps API

		GMaps.geocode({
			address: address,
			callback: function(results, status) {

				if (status !== 'OK') return;

				var latlng = results[0].geometry.location;

				self.setState({
					currentAddress: results[0].formatted_address,
					mapCoordinates: {
						lat: latlng.lat(),
						lng: latlng.lng()
					}
				});

			}
		});

	},

	render(){

		return (

			<div>
				<h1>Your Google Maps Locations</h1>

				<Search onSearch={this.searchForAddress} />

				<Map lat={this.state.mapCoordinates.lat} lng={this.state.mapCoordinates.lng} />

				<CurrentLocation address={this.state.currentAddress} 
					favorite={this.isAddressInFavorites(this.state.currentAddress)} 
					onFavoriteToggle={this.toggleFavorite} />

				<LocationList locations={this.state.favorites} activeLocationAddress={this.state.currentAddress} 
					onClick={this.searchForAddress} />

			</div>

		);
	}

});

module.exports = App;

In the render method, we initialize the other components. Each component receives only the data that it needs to get its job done, as attributes. In some places, we also pass methods which the child components will call, which is a good way for components to communicate while keeping them isolated from one another.

CurrentLocation.js

Next is CurrentLocation. This component presents the address of the currently displayed location in an H4 tag, and a clickable star icon. When the icon is clicked, the App’s toggleFavorite method is called.

var React = require('react');

var CurrentLocation = React.createClass({

	toggleFavorite(){
		this.props.onFavoriteToggle(this.props.address);
	},

	render(){

		var starClassName = "glyphicon glyphicon-star-empty";

		if(this.props.favorite){
			starClassName = "glyphicon glyphicon-star";
		}

		return (
			<div className="col-xs-12 col-md-6 col-md-offset-3 current-location">
				<h4 id="save-location">{this.props.address}</h4>
				<span className={starClassName} onClick={this.toggleFavorite} aria-hidden="true"></span>
			</div>
		);
	}

});

module.exports = CurrentLocation;

LocationList.js

LocationList takes the array with favorite locations that was passed to it, creates a LocationItem object for each and presents it in a Bootstrap list group.

var React = require('react');
var LocationItem = require('./LocationItem');

var LocationList = React.createClass({

	render(){

		var self = this;

		var locations = this.props.locations.map(function(l){

			var active = self.props.activeLocationAddress == l.address;

			// Notice that we are passing the onClick callback of this
			// LocationList to each LocationItem.

			return <LocationItem address={l.address} timestamp={l.timestamp} 
					active={active} onClick={self.props.onClick} />
		});

		if(!locations.length){
			return null;
		}

		return (
			<div className="list-group col-xs-12 col-md-6 col-md-offset-3">
				<span className="list-group-item active">Saved Locations</span>
				{locations}
			</div>
		)

	}

});

module.exports = LocationList;

LocationItem.js

LocationItem represents an individual favorite location. It uses the moment library to calculate the relative time since the location was added as a favorite.

var React = require('react');
var LocationItem = require('./LocationItem');
var moment = require('moment');

var LocationItem = React.createClass({

	handleClick(){
		this.props.onClick(this.props.address);
	},

	render(){

		var cn = "list-group-item";

		if(this.props.active){
			cn += " active-location";
		}

		return (
			<a className={cn} onClick={this.handleClick}>
				{this.props.address}
				<span className="createdAt">{ moment(this.props.timestamp).fromNow() }</span>
				<span className="glyphicon glyphicon-menu-right"></span>
			</a>
		)

	}

});

module.exports = LocationItem;

Map.js

Map is a special component. It wraps the Gmaps plugin, which is not a React component by itself. By hooking to the Map’s componentDidUpdate method, we can initialize a real map inside the #map div whenever the displayed location is changed.

var React = require('react');

var Map = React.createClass({

	componentDidMount(){

		// Only componentDidMount is called when the component is first added to
		// the page. This is why we are calling the following method manually. 
		// This makes sure that our map initialization code is run the first time.

		this.componentDidUpdate();
	},

	componentDidUpdate(){

		if(this.lastLat == this.props.lat && this.lastLng == this.props.lng){

			// The map has already been initialized at this address.
			// Return from this method so that we don't reinitialize it
			// (and cause it to flicker).

			return;
		}

		this.lastLat = this.props.lat;
		this.lastLng = this.props.lng

		var map = new GMaps({
			el: '#map',
			lat: this.props.lat,
			lng: this.props.lng
		});

		// Adding a marker to the location we are showing
		
		map.addMarker({
			lat: this.props.lat,
			lng: this.props.lng
		});
	},

	render(){

		return (
			<div className="map-holder">
				<p>Loading...</p>
				<div id="map"></div>
			</div>
		);
	}

});

module.exports = Map;

Search.js

The Search component consists of a Bootstrap form with an input group. When the form is submitted the App’s searchForAddress method is called.

var React = require('react');

var Search = React.createClass({

	getInitialState() {
		return { value: '' };
	},

	handleChange(event) {
		this.setState({value: event.target.value});
	},

	handleSubmit(event){
		
		event.preventDefault();
		
		// When the form is submitted, call the onSearch callback that is passed to the component

		this.props.onSearch(this.state.value);

		// Unfocus the text input field
		this.getDOMNode().querySelector('input').blur();
	},

	render() {

		return (
			<form id="geocoding_form" className="form-horizontal" onSubmit={this.handleSubmit}>
				<div className="form-group">
					<div className="col-xs-12 col-md-6 col-md-offset-3">
						<div className="input-group">
							<input type="text" className="form-control" id="address" placeholder="Find a location..." 
							value={this.state.value} onChange={this.handleChange} />
							<span className="input-group-btn">
								<span className="glyphicon glyphicon-search" aria-hidden="true"></span>
							</span>
						</div>
					</div>
				</div>
			</form>
		);

	}
});

module.exports = Search;

main.js

All that is left is to add the App component to the page. I am adding it to a container div with the #main id (you can see this element in index.html in the downloadable zip file).

var React = require('react');
var App = require('./components/App');

React.render(
  <App />,
  document.getElementById('main')
);

In addition to these files, I have included the GMaps library and the Google Maps JavaScript API on which it depends, as tags in index.html.

Ready!

I hope that this tutorial gave you a better understanding of how to structure React applications. There is much more you can do with the library, including server-side rendering, which we hope to cover in the future.

Source:: Tutorialzine.com

Freebie: 5 Elegant and Responsive Sidebar Templates

By Danny Markov

5-elegant-and-responsive-sidebar-templates

In this post we want to share with you 5 elegant responsive templates for sidebars that you can download and use straight away in your designs. This continues our collection of freebies, created by us to save you time on your projects (which you can spend coding/gaming instead).

The Design

All of the sidebars are responsive and on smaller screens turn from vertical to horizontal. Each example has it’s 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. Our sidebars don’t use Bootstrap or other frontend frameworks.

Some of the templates come with short JavaScript snippets, which are jQuery dependent, so make sure to copy them together with a link to jQuery via CDN or local file. Other dependencies to watch out for are font-awesome for the social icons and the Cookie font on some of the sidebars.

Elegant Sidebar Templates

Free for Commercial Use

These templates are free to use in any commercial or non-commercial projects. You can check our license for more info. We hope that you like them!

Source:: Tutorialzine.com

New number and Math features in ES6

By Axel Rauschmayer

This blog post describes the new number and Math features of ECMAScript 6.

Overview

You can now specify integers in binary and octal notation:

    > 0xFF // ES5: hexadecimal
    255
    > 0b11 // ES6: binary
    3
    > 0o10 // ES6: octal
    8

The global object Number gained a few new properties. Among others:

  • Number.EPSILON for comparing
  • Methods and constants for determining whether an integer is within the signed 53 bit range that can be safely represented by JavaScript.

New integer literals

ECMAScript 5 already has literals for hexadecimal integers:

    > 0x9
    9
    > 0xA
    10
    > 0x10
    16
    > 0xFF
    255

ECMAScript 6 brings two new kinds of integer literals:

  • Binary literals have the prefix 0b or 0B:

        > 0b11
        3
        > 0b100
        4
    
  • Octal literals have the prefix 0o or 0O (yes, that’s a zero followed by the capital letter O; you’ll be fine if you use the first variant):

        > 0o7
        7
        > 0o10
        8
    

Remember that the method Number.prototype.toString(radix) can be used to convert numbers back:

    > (255).toString(16)
    'ff'
    > (4).toString(2)
    '100'
    > (8).toString(8)
    '10'

Use case for octal literals: Unix-style file permissions

In the Node.js file system module, several functions have the parameter mode. Its value is used to specify file permissions, via an encoding that is a holdover from Unix:

  • Permissions are specified for three categories of users:
    • User: the owner of the file
    • Group: the members of the group associated with the file
    • All: everyone
  • Per category, the following permissions can be granted:
    • r (read): the users in the category are allowed to read the file
    • w (write): the users in the category are allowed to change the file
    • x (execute): the users in the category are allowed to run the file

That means that permissions can be represented by 9 bits (3 categories with 3 permissions each):

User Group All
Permissions r, w, x r, w, x r, w, x
Bit 8, 7, 6 5, 4, 3 2, 1, 0

The permissions of a single category of users are stored in 3 bits:

Bits Permissions Octal digit
000 ––– 0
001 ––x 1
010 –w– 2
011 –wx 3
100 r–– 4
101 r–x 5
110 rw– 6
111 rwx 7

That means that octal numbers are a compact representation of all permissions, you only need 3 digits, one digit per category of users. Two examples:

  • 755 = 111,101,101: I can change, read and execute; everyone else can only read and execute.
  • 640 = 110,100,000: I can read and write; group members can read; everyone can’t access at all.

parseInt() and the new integer literals

parseInt() has the following signature:

    parseInt(string, radix?)

It provides special support for the hexadecimal literal notation – the prefix 0x (or 0X) of string is removed if:

  • radix is missing or 0. Then radix is set to 16.
  • radix is already 16.

For example:

    > parseInt('0xFF')
    255
    > parseInt('0xFF', 0)
    255
    > parseInt('0xFF', 16)
    255

In all other cases, digits are only parsed until the first non-digit:

    > parseInt('0xFF', 10)
    0
    > parseInt('0xFF', 17)
    0

parseInt() does not have special support for binary or octal literals!

    > parseInt('0b111')
    0
    > parseInt('0b111', 2)
    0
    > parseInt('111', 2)
    7
    
    > parseInt('0o10')
    0
    > parseInt('0o10', 8)
    0
    > parseInt('10', 8)
    8

If you want to parse these kinds of literals, you need to use Number():

    > Number('0b111')
    7
    > Number('0o10')
    8

New Number constructor properties

This section describes new properties that the constructor Number has picked up in ECMAScript 6.

Previously global functions

Four number-related functions are already available as global functions and have been added (with no or little modifications) to Number, as methods: isFinite, isNaN, parseFloat and parseInt.

Number.isFinite(number)

Is number an actual number (neither Infinity nor -Infinity nor NaN)?

    > Number.isFinite(Infinity)
    false
    > Number.isFinite(-Infinity)
    false
    > Number.isFinite(NaN)
    false
    > Number.isFinite(123)
    true

The advantage of this method is that it does not coerce its parameter to number (whereas the global function does):

    > Number.isFinite('123')
    false
    > isFinite('123')
    true
Number.isNaN(number)

Is number the value NaN? Making this check via === is hacky. NaN is the only value that is not equal to itself:

    > let x = NaN;
    > x === NaN
    false

Therefore, this expression is used to check for it

    > x !== x
    true

Using Number.isNaN() is more self-descriptive:

    > Number.isNaN(x)
    true

Number.isNan() also has the advantage of not coercing its parameter to number (whereas the global function does):

    > Number.isNaN('???')
    false
    > isNaN('???')
    true
Number.parseFloat and Number.parseInt

The following two methods work exactly like the global functions with the same names. They were added to Number for completeness sake; now all number-related functions are available there.

  • Number.parseFloat(string)
  • Number.parseInt(string, radix)

Number.EPSILON

Especially with decimal fractions, rounding errors can become a problem in JavaScript. For example, the

    > 0.1 + 0.2 === 0.3
    false

Number.EPSILON specifies a reasonable margin of error when comparing floating point numbers. It provides a better way to compare floating point values, as demonstrated by the following function.

    function epsEqu(x, y) {
        return Math.abs(x - y) < Number.EPSILON;
    }
    console.log(epsEqu(0.1+0.2, 0.3)); // true

Number.isInteger(number)

JavaScript has only floating point numbers (doubles). Accordingly, integers are simply floating point numbers without a decimal fraction.

Number.isInteger(number) returns true if number is a number and does not have a decimal fraction.

    > Number.isInteger(-17)
    true
    > Number.isInteger(33)
    true
    > Number.isInteger(33.1)
    false
    > Number.isInteger('33')
    false
    > Number.isInteger(NaN)
    false
    > Number.isInteger(Infinity)
    false

Safe Integers

JavaScript numbers have only enough storage space to represent 53 bit signed integers. That is, integers i in the range −2^53^ < i < 2^53^ are safe. What exactly that means is explained momentarily. The following properties help determine whether a JavaScript integer is safe:

  • Number.isSafeInteger(number)
  • Number.MIN_SAFE_INTEGER
  • Number.MAX_SAFE_INTEGER

The notion of safe integers centers on how mathematical integers are represented in JavaScript. In the range (−2^53^, 2^53^) (excluding the lower and upper bounds), JavaScript integers are safe: there is a one-to-one mapping between them and the mathematical integers they represent.

Beyond this range, JavaScript integers are unsafe: two or more mathematical integers are represented as the same JavaScript integer. For example, starting at 2^53^, JavaScript can represent only every second mathematical integer:

    > Math.pow(2, 53)
    9007199254740992
    
    > 9007199254740992
    9007199254740992
    > 9007199254740993
    9007199254740992
    > 9007199254740994
    9007199254740994
    > 9007199254740995
    9007199254740996
    > 9007199254740996
    9007199254740996
    > 9007199254740997
    9007199254740996

Therefore, a safe JavaScript integer is one that unambiguously represents a single mathematical integer.

The properties of Number

The two Number properties specifying the lower and upper bound of safe integers could be defined as follows:

    Number.MAX_SAFE_INTEGER = Math.pow(2, 53)-1;
    Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;

Number.isSafeInteger() determines whether a JavaScript number is a safe integer and could be defined as follows:

    Number.isSafeInteger = function (n) {
        return (typeof n === 'number' &&
            Math.round(n) === n &&
            Number.MIN_SAFE_INTEGER <= n &&
            n <= Number.MAX_SAFE_INTEGER);
    }

For a given value n, this function first checks whether n is a number and an integer. If both checks succeed, n is safe if it is greater than or equal to MIN_SAFE_INTEGER and less than or equal to MAX_SAFE_INTEGER.

Safe results of arithmetic computations

How can we make sure that results of arithmetic computations are correct? For example, the following result is clearly not correct:

    > 9007199254740990 + 3
    9007199254740992

We have two safe operands, but an unsafe result:

    > Number.isSafeInteger(9007199254740990)
    true
    > Number.isSafeInteger(3)
    true
    > Number.isSafeInteger(9007199254740992)
    false

The following result is also incorrect:

    > 9007199254740995 - 10
    9007199254740986

This time, the result is safe, but one of the operands isn’t:

    > Number.isSafeInteger(9007199254740995)
    false
    > Number.isSafeInteger(10)
    true
    > Number.isSafeInteger(9007199254740986)
    true

Therefore, the result of applying an integer operator op is guaranteed to be correct only if all operands and the result are safe. More formally:

    isSafeInteger(a) && isSafeInteger(b) && isSafeInteger(a op b)

implies that a op b is a correct result.

Source of this section

Math

The global object Math has several new methods in ECMAScript 6.

Various numerical functionality

Math.sign(x)

Returns the sign of x as -1 or +1. Unless x is either NaN or zero; then x is returned[1].

[1]: While that is something that you normally don’t see, that means that -0 produces the result -0 and +0 produces the result +0.

    > Math.sign(-8)
    -1
    > Math.sign(3)
    1
    
    > Math.sign(0)
    0
    > Math.sign(NaN)
    NaN
    
    > Math.sign(-Infinity)
    -1
    > Math.sign(Infinity)
    1
Math.trunc(x)

Removes the decimal fraction of x.

    > Math.trunc(3.1)
    3
    > Math.trunc(3.9)
    3
    > Math.trunc(-3.1)
    -3
    > Math.trunc(-3.9)
    -3
Math.cbrt(x)

Returns the cube root of x (∛x).

    > Math.cbrt(8)
    2

Using 0 instead of 1 with exponentiation and logarithm

JavaScript numbers (doubles) close to zero are stored with a higher precision.

1 × 10^−16^

    > 1e-16 === 0
    false
    > 1 + 1e-16 === 1
    true
Math.expm1(x)

Returns Math.exp(x)-1. The inverse of Math.log1p().

Therefore, this method provides higher precision whenever Math.exp() has results close to 1.

    > Math.expm1(1e-10)
    1.00000000005e-10
    > Math.exp(1e-10)-1
    1.000000082740371e-10
    > var Decimal = require('decimal.js').config({precision:50});
    > new Decimal(1e-10).exp().minus(1).toString()
    '1.000000000050000000001666666666708333333e-10'
Math.log1p(x)

Returns Math.log(1 + x). The inverse of Math.expm1().

Therefore, this method lets you specify parameters that are close to 1 with a higher precision.

We have already established that 1 + 1e-16 === 1. Therefore, it is no surprise that the following two calls of log() produce the same result:

    > Math.log(1 + 1e-16)
    0
    > Math.log(1 + 0)
    0

In contrast, log1p() produces different results:

    > Math.log1p(1e-16)
    1e-16
    > Math.log1p(0)
    0

Logarithms to base 2 and 10

Math.log2(x)

Computes the logarithm to base 2.

    > Math.log2(8)
    3
Math.log10(x)

Computes the logarithm to base 10.

    > Math.log10(100)
    2

Support for compiling to JavaScript

Emscripten pioneered a coding style that was later picked up by asm.js: The operations of a virtual machine (think bytecode) are expressed in static subset of JavaScript. That subset can be executed efficiently by JavaScript engines: If it is the result of a compilation from C++, it runs at about 70% of native speed.

Math.fround(x)

Rounds x to a 32 bit floating point value (float). Used by asm.js to tell an engine to internally use a float value.

Math.imul(x, y)

Multiplies the two 32 bit integers x and y and returns the lower 32 bits of the result. This is the only 32 bit basic math operation that can’t be simulated by using a JavaScript operator and coercing the result back to 32 bits. For example, idiv could be implemented as follows:

    function idiv(x, y) {
        return (x / y) | 0;
    }

In contrast, multiplying two large 32 bit integers may produce a double that is so large that lower bits are lost.

Bitwise operations

  • Math.clz32(x)
    Counts the leading zero bits in the 32 bit integer x.

        > Math.clz32(0b01000000000000000000000000000000)
        1
        > Math.clz32(0b00100000000000000000000000000000)
        2
        > Math.clz32(2)
        30
        > Math.clz32(1)
        31
    

Trigonometric methods

  • Math.sinh(x)
    Computes the hyperbolic sine of x.

  • Math.cosh(x)
    Computes the hyperbolic cosine of x.

  • Math.tanh(x)
    Computes the hyperbolic tangent of x.

  • Math.asinh(x)
    Computes the inverse hyperbolic sine of x.

  • Math.acosh(x)
    Computes the inverse hyperbolic cosine of x.

  • Math.atanh(x)
    Computes the inverse hyperbolic tangent of x.

  • Math.hypot(...values)
    Computes the square root of the sum of squares of its arguments.

Source:: 2ality

Our Favorite jQuery Plugins and Libraries For Spring 2015

By Nick Anastasov

our-favorite-jquery-plugins-libraries-spring-2015

Web development is hard and there is much to learn. Developers and designers need to be on top of a lot of emerging technologies and trends. But the community is buzzing with activity and it creates awesome libraries and plugins that can help us do our work. Here are some of our favorites. Not all of them were released this year, but all of them were updated in the last few months and are a great addition to your bookmarks.

1. Animsition

Animsition is a simple and easy jQuery plugin for CSS animated page transitions. Over 50 animations are available such as different fade outs, rotations and flips. Just a friendly tip: use it with moderation! Github.

Animsition

2. Waves

Waves is a plugin that recreates the on-click ink effect as seen in Google’s Material Design. The effect can be applied to any HTML element – buttons, links, images and more. Github.

Waves

Waves

3. Interdimensional

This is an interesting library which allows you to scroll a web page by tilting your smartphone. It obviously doesn’t work on laptops and desktops, but we think it is a novel approach for interacting with the web. Github.

Interdimensional

Interdimensional

4. Unite Gallery

Unite Gallery is multipurpose JavaScript gallery based on jQuery. It supports images, video and music, and is responsive and touch friendly. It is skinnable and themeable and has a powerful api. Github.

Unite Gallery

Unite Gallery

5. Scrollify

Scrollify is a jQuery plugin that assists scrolling and smoothly snaps to sections. Fully configurable and optimised for touch. This plugin is a power steering for your scroll wheel. Github.

Scrollify

Scrollify

6. SweetAlert

SweetAlert is a beautiful replacement for javascript’s alert. It uses smooth CSS transitions and animations for a nice visual experience. It’s also responsive and will look great no matter what you’re using – a desktop computer, smartphone or tablet. Github.

SweetAlert

SweetAlert

7. Oh Snap

Oh Snap is a simple notification jQuery/Zepto library designed to be used in mobile apps but works just as well on other devices. Github.

Oh Snap

Oh Snap

8. Tipso

Tipso is a lightweight responsive jQuery tooltip plugin with lots of options for customization. A WordPress version of the plugin is also available. Github.

Tipso

Tipso

9. Material Design Preloader

A jQuery plugin that recreates the Material Design preloader (as seen on Gmail’s inbox). Github.

Material Design Preloader

Material Design Preloader

10. Tabulous

Tabulous.js is a cool plugin that helps you create tabbed content with awesome transition when changing between tabs. It can be used with any contents you want and is really simple to use. Github.

Tabulous

Tabulous

11. Vivus

Vivus is a lightweight JavaScript class (with no dependencies) that allows you to animate SVGs, giving them the appearence of being drawn line by line. There are a variety of different animations available, as well as the option to create a custom script to draw your SVG in whatever way you like. Github.

Vivus

Vivus

12. Midnight

A jQuery plugin that switches between multiple header designs as you scroll, so you always have a header that looks great with the content below it. Github.

Midnight

Midnight

13. Fake Loader

Fake Loader is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulate the page preloading effect. Github.

Fake Loader

Fake Loader

14. Labelauty

A jQuery plugin that styles checkboxes and radio buttons and allows for the content inside labels to change depending on checked/unchecked status. Github.

Labelauty

Labelauty

15. Scrolline

Scrolline is a jQuery plugin which shows a progress indicator near the top of the window, which gives users a hint on how far they’ve scrolled. This is suitable for mobile devices where scroll bars are hidden by default. Github.

Scrolline

Scrolline

16. jQuery Timer

This plugin turns an element on the page into a fully functional, lightweight timer. Easily create callback functions to be executed after a certain duration or repeatedly at an interval. You can also pause and resume. Github.

jQuery Timer

jQuery Timer

17. Textures

Textures.js is a Javascript library for creating scalable SVG patterns. It is designed for visualizing and presenting data like maps, and is built on top of d3.js. Github.

Textures

Textures

18. Gridder

A jQuery plugin that displays a thumbnail grid with expanding previews, similar to the effect seen on Google Images, allowing you to quickly see more details without having to reload the page. Github.

Gridder

Gridder

19. Tweet Parser

Correctly parse elements containing tweets and turn URLS, @users & #hashtags into working urls. Github.

jQuery Twitter Parser

Tweet Parser

20. Zelect

This is lightweight and customizable replacement for the plain element. You can style any aspect of it with simple CSS so that it matches the rest of your web application. Github.

Zelect

Zelect

21. JS Grid

JS Grid is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging and sorting. Github.

JS Grid

JS Grid

22. Mapael

jQuery Mapael is a jQuery plugin based on raphael.js that allows you to display dynamic vector maps. As seen from the demos, with Mapael, you can display a map of the world with clickable countries and much more. Github.

jQuery Mapael

jQuery Mapael

23. Payform

Payform is a useful plugin that lets you easily create, validate and format credit card forms. Github.

Payform

Payform

Source:: Tutorialzine.com

Deploying ECMAScript 6

By Axel Rauschmayer

This blog post describes the options you have for deploying ECMAScript 6 in current JavaScript environments. It is selective w.r.t. the amount of tools it covers. If you want a comprehensive list of tools, I suggest you look at Addy Osmani’s “ECMAScript 6 Tools”.

Consult the blog post “Using ECMAScript 6 today” for an overview of ES6 features.

Using ECMAScript 6 today

What options do you have for using ECMAScript 6 today?

ECMAScript 6 features are continually appearing in engines. You can look up which ones are already supported where in Kangax’ “ECMAScript 6 compatibility table”. I’d expect first JavaScript engines to fully support ES6 in late 2015 or early 2016. It will take longer until all current engines do so.

Especially if you take support for legacy engines into consideration, compiling ES6 to ES5 will be the only viable option for using ES6 for quite a while. Compiling from source code to source code is also called transpiling. You can transpile ES6 either before deployment (statically) or at runtime (dynamically). The next section explains how that works, later sections describe other ES6 tools and libraries.

The nice thing about ES6 is that it is a superset of ES5, which means that all of your ES5 code bases are already valid ES6. This helps tremendously with adopting ES6-specific features, because you can do so incrementally.

Using ECMAScript 6 natively

As soon as the first engine fully supports ES6 and until all non-ES6 engines go away, a hybrid approach could be used for client-side apps:

  • The server has two versions of each file: the native ES6 version and its transpilation, an ES5 version.
  • When the web app starts, feature detection is used to check whether ES6 is fully supported. If it is, the ES6 version of the app is used. Otherwise, the ES5 version is used. How exactly this process is going to work is not clear yet, no best practices have been established, so far.

npm may eventually support two versions of the same module, which would enable you to deliver libraries as both ES5 and ES6 for Node.js, io.js and client-side module systems that are based on npm.

Transpilation tools

There are three essential choices that you have to make for transpilation:

  • A transpiler (for your code)
  • A package manager (to install existing libraries)
  • A module system (for the complete app)

Note that the choices are not completely independent, not every module system works with every package manager etc. The next sections explain each of these choices in more detail.

Choosing a transpiler

A transpiler compiles your ES6 code to ES5. Popular choices are:

  • TypeScript: Is basically ECMAScript 6 plus optional type annotations.
  • Traceur (pronounced “tray-SOOR”): is an ES6 transpiler by Google, the first popular one.
  • Babel (pronounced “babble”): is a newer ES6 transpiler that whose popularity has grown tremendously recently. Babel supports React’s JSX syntax in addition to ES6.

You can transpile the code either:

  • Statically (before deployment)
  • Dynamically (at runtime)
Static transpilation

As a build step, TypeScript, Traceur and Babel let you produce ES5 code in the following module formats. You can either invoke them directly or use a build tool (grunt, gulp, broccoli, etc.).

  • AMD
  • CommonJS
  • ES6 module loader API: The ES6 code is transpiled to ES5 code that uses this API via a polyfill. This format is not supported by TypeScript.

In browsers, such ES5 modules are loaded via one of the module systems described later.
On Node.js, you can use the built-in module system (other options exist, e.g. webpack and the ES6 Module Loader Polyfill).

Dynamic transpilation

In browsers, you transpile dynamically via a library plus a custom . This option exists for Traceur and Babel.

For Node.js, Babel has tools for on-the-fly compilation. These are described in a separate blog post.

Choosing a package manager

You need a package manager for installing third-party libraries. These are three popular ones:

  • npm (CommonJS modules): is a package manager that was originally created for Node.js, but has grown in popularity for client-side development thanks to module packaging and loading tools such as browserify and webpack.
  • Bower (CommonJS or AMD modules): is a package manager for client-side code.
  • jspm: is a package manager for SystemJS (see next bullet list). It can install modules from a variety of sources, including GitHub and npm.

Choosing a module system

Module systems bring support for modules to ES5 browsers (Node.js has a built-in module system). That way, you can build your app out of modules – your own and library modules. Popular module systems are:

  • RequireJS: is a loader for AMD modules, which can be statically created via TypeScript, Traceur or Babel. Loader plugins (based on Traceur and Babel) enable it to load ES6 modules.
  • Browserify: packages CommonJS modules (including ones installed via npm) so that they can be loaded in browsers. Supports ES6 modules via transforms (plugins) based on Traceur and Babel.
  • webpack: a packager and loader for either CommonJS modules (including ones installed via npm) or AMD modules (including ones installed via Bower). Supports ES6 modules via custom loaders (plugins) based on Traceur and Babel.
  • SystemJS: A module system based on the ES6 Module Loader Polyfill that supports ES6 modules and the ES5 module formats CommonJS, AMD and “ES6 module loader API”.

Example setups

Separate blog posts describe three example setups:

Other useful ES6 tools and libraries

  • Test tools (such as Jasmine and mocha) can mostly be used as is, because they work with the transpiled code and don’t have to understand the original ES6 code. Babel’s documention has information on how to use it with various test tools.

  • The following linters all support ES6, but to varying degrees:

    • JSLint (focus: enforcing coding practices)
    • JSHint (focus: enforcing coding practices)
    • ESLint (focus: letting people implement their own style rules)
    • JSCS (focus: enforcing code style)
  • Shims/polyfills enable you to use much of the ECMAScript 6 standard library in ES5 code:

  • ES6 parsers:

ES6 REPLs

There are many REPLs (command lines) out there for interactively playing with ES6. The obvious choices are the interactive online playgrounds of the following projects:

Additionally, Babel brings ES6 support to the Node.js REPL via its babel-node tool.

What ES6 features can be transpiled?

ECMAScript 6 has three kinds of features:

  • Better syntax for existing features
  • New functionality in the standard library
  • Completely new features

Better syntax for existing features

For example:

  • Classes
  • Modules

These can be relatively easily compiled to ES5. For example, this is an ES6 class:

    class Point {
        constructor() {
            this.x = x;
            this.y = y;
        }
        toString() {
            return `(${this.x}, ${this.y})`;
        }
    }

In loose mode, Babel produces nicer ES5 code, at the cost of not being completely faithful to ES6 semantics. This is the previous code, transpiled in loose mode:

    "use strict";
    
    var _classCallCheck = function (instance, Constructor) {
        if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
        }
    };
    
    var Point = (function () {
        function Point() {
            _classCallCheck(this, Point);
    
            this.x = x;
            this.y = y;
        }
    
        Point.prototype.toString = function toString() {
            return "(" + this.x + ", " + this.y + ")";
        };
    
        return Point;
    })();

New functionality in the standard library

For example:

  • New methods for strings, arrays
  • Promises
  • Maps, Sets

These can be provided via a library. Much of that functionality (such as String.prototype.repeat()) is even useful for ES5. A later section lists a few such libraries.

Completely new features

These features can never be transpiled completely faithfully. But some of them have reasonable simulations, for example:

  • let and const
  • Symbols
  • Generators

Others are impossible to transpile:

  • Proxies
  • WeakMaps and WeakSets
  • Subclassable built-in constructors (e.g. Error and Array can be subclassed in ES6)

Source:: 2ality

node-es6-transpiled

By Axel Rauschmayer

This blog post explains how to use ES6 on Node.js by transpiling it to ES5 via Babel.

A previous blog post showed how to dynamically transpile ES6 at runtime (also via Babel). That is more convenient and should work for most projects, but occasionally you may want a simpler and faster setup for your runtime environment.

Installation

Installation consists of downloading the repository node-es6-demo and executing the following commands, which install all npm packages that the repository depends on:

    $ cd node-es6-demo/
    $ npm install

The repo has the following structure:

    node-es6-demo/
        es5/
        es6/
            myapp.js
        gulpfile.js

Source maps

Source maps help whenever a language is compiled to JavaScript. Compiling source code to source code is also called transpiling. Examples of transpilation include:

  • Minification (normal JavaScript to minified JavaScript)
  • CoffeeScript
  • ECMAScript 6 (ES6 to ES5)

A source map is a file that accompanies the transpilation result and maps the lines of the result to lines in the transpiled files. This information can be used by error messages and debuggers to refer to lines in the original instead of the transpilation result. There are two ways to let tools know about a source map: Either the transpilation output refers to the source map file in its last line or it embeds the file’s contents in that line.

For more information on source maps consult the article “Introduction to JavaScript Source Maps” by Ryan Seddon on HTML5 Rocks.

The gulp file

I am handling transpilation via the build tool gulp. It is configured via a file gulpfile.js in a project’s directory. Ours looks as follows:

    var gulp = require('gulp');
    var sourcemaps = require('gulp-sourcemaps');
    var babel = require('gulp-babel');
    
    var path = require('path');
    
    var paths = {
        es6: ['es6/**/*.js'],
        es5: 'es5',
        // Must be absolute or relative to source map
        sourceRoot: path.join(__dirname, 'es6'),
    };
    gulp.task('babel', function () { // (A)
        return gulp.src(paths.es6)
            .pipe(sourcemaps.init()) // (B)
            .pipe(babel())
            .pipe(sourcemaps.write('.', { sourceRoot: paths.sourceRoot })) // (C)
            .pipe(gulp.dest(paths.es5));
    });
    gulp.task('watch', function() { // (D)
        gulp.watch(paths.es6, ['babel']);
    });
    gulp.task('default', ['watch']); // (E)

In order to make gulp do something you invoke it like this:

    $ gulp "name_of_task»

Our gulpfile defines two tasks:

  • babel (line (A)) transpiles the ES6 files in es6/ to ES5 files in es5/.
  • watch (line (D)) continuously watches the ES6 files and transpiles them whenever they are changed.

If you call gulp without any arguments, the default task (line (E)) is triggered. In this file, the default task is watch.

Source maps are created due to the code in line (B) and line (C).

Hopefully you now have a rough understanding of how the gulp file works. For open questions, consult the gulp documentation.

Transpilation

The file es6/myapp.js contains the ES6 code of the Node.js application:

    require('source-map-support').install();
    
    console.log([1,2,3].map(x => x * x));
    
    throw new Error('Test!');

Alas, Node.js does not come with built-in support for source maps. But it can be enabled via a library, e.g. the npm package source-map-support. That library needs to be called at least once in an app. The first line in the previous code takes care of that.

The following gulp invocation transpiles myapp.js.

    $ gulp babel

Alternatively, you can use gulp or gulp watch to continuously watch the ES6 files and transpile them whenever they are changed.

The results of the transpilation are in the directory es5/:

    node-es6-demo/
        es5/
            myapp.js
            myapp.js.map

You can see the ES5 version of es6/myapp.js and the source map file myapp.js.map. The contents of the former file are:

    'use strict';
    
    require('source-map-support').install();
    
    console.log([1, 2, 3].map(function (x) {
      return x * x;
    }));
    
    throw new Error('Test!');
    //# sourceMappingURL=myapp.js.map

Running the transpiled code

The transpiled code is a normal ES5 Node.js app and is run as usual:

    $ node es5/myapp.js

It produces the following output. Note that, thanks to the source map, the stack trace reports that the exception is thrown in line 5. That is the correct line in the ES6 file.

    [ 1, 4, 9 ]
    
    /tmp/node-es6-demo/es6/myapp.js:5
    throw new Error('Test!');
          ^
    Error: Test!
        at Object.<anonymous> (/tmp/node-es6-demo/es6/myapp.js:5:7)
        at Module._compile (module.js:456:26)
        at Object.Module._extensions..js (module.js:474:10)
        at Module.load (module.js:356:32)
        at Function.Module._load (module.js:312:12)
        at Function.Module.runMain (module.js:497:10)
        at startup (node.js:119:16)
        at node.js:906:3

Source:: 2ality

Writing client-side ES6 with webpack

By Axel Rauschmayer

webpack is a client-side module builder and module loader. This blog post shows you how to write ECMAScript 6 code with it.

The code shown here is on GitHub, in the project webpack-es6-demo.

webpack features

Notable webpack features include:

  • Supported module formats: AMD, CommonJS
    • Via loader (plug-in): ES6
  • Supported package managers: Bower, npm
  • Loaders for non-code: CSS, templates, …
  • On-demand loading (chunked transfer)
  • Built-in development server

Installing webpack

Install webpack:

    npm install -g webpack

Enable support for ECMAScript 6 (via Babel):

  • Per project: npm install babel-loader --save-dev
  • In your home directory: cd $HOME ; npm install babel-loader
  • Globally: npm install -g babel-loader

Using webpack and ES6 in a project

The demo project webpack-es6-demo has the following structure:

    webpack-es6-demo/
        es6/
            Point.js
            main.js
        index.html
        webpack.config.js

The following command compiles the ES6 files es6/Point.js and es6/main.js to a file bundle.js:

    webpack --watch

After executing the previous command, you can open index.html in a web browser (directly from the file system if you’d like). index.html runs bundle.js, which means that you get to see what main.js is doing.

In real-world projects, you probably won’t use webpack directly, but via build tools, such as grunt, gulp, etc.

webpack.config.js

This is the configuration file for webpack:

    var path = require('path');
    module.exports = {
        entry: './es6/main.js',
        output: {
            path: __dirname,
            filename: 'bundle.js'
        },
        module: {
            loaders: [
                { test: path.join(__dirname, 'es6'),
                  loader: 'babel-loader' }
            ]
        }
    };

Things work as follows:

  • Input: is specified via the property entry. This is where the execution of JavaScript code starts.
  • Output: webpack bundles the entry file and everything it depends on into the output file bundle.js (which resides in the same directory as webpack.config.js).
  • Support for ES6: is enabled via a the module loader babel-loader.
    • Property test: specifies what files the loader should be used for.
      • Single test: regular expression or string with an absolute path
      • Multiple tests: array of single tests (logical “and”)

HTML

The HTML file starts JavaScript via the bundle file that was created by webpack.

    <!doctype html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>webpack ES6 demo</title>
    </head>
    <body>
    <script src="bundle.js"></script>
    </body>
    </html>

ECMAScript 6 code

The following two ECMAScript 6 files were packaged into bundle.js.

main.js:

    import Point from './Point.js';
    var body = document.querySelector('body');
    body.textContent = 'Good point: ' + new Point(1, 23);

Point.js:

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString() {
            return '('+this.x+','+this.y+')';
        }
    }
    export default Point;

Note that the paths follow Node.js conventions.

Using npm packages

You can install packages via npm and use them from your ES6 code, seamlessly. For example: First install lodash.

    $ mkdir node_modules
    $ npm install lodash

Then use it anywhere in your ES6 code:

    import { zip } from 'lodash';
    console.log(zip(['1', '2'], ['a', 'b']));

Alternatives to webpack

If webpack is not your cup of tea, there are several capable alternatives for writing client-side ES6 code. For example:

webpack, jspm and Browserify can also use Traceur instead of Babel, if you want to.

Source:: 2ality