Monday, August 1, 2016

15 Fresh JavaScript Libraries for June 2016

Are you a JavaScript developer and looking for some new and fresh JavaScript libs for your next project then you are at right place. We have embarked ourselves and got some of the best and fresh JavaScript Libraries for the month of June 2016.

So, get ready for the latest and handy JavaScript Libraries we covered in this article, this article includes feature enriched and interactive JavaScript Libraries that offer you several functions and can serve number of purposes for you to build effective and useful web applications.

1. Shepherd

https://school.codequs.com/p/HJqC6dN_

Shepherd is a JavaScript library for guiding users through your app. It uses Tether, another open source library, to position all of its steps.

2. Tingle.js

https://school.codequs.com/p/HJqC6dN_

Tingle.js is a minimalist and easy-to-use modal plugin written in pure JavaScript. it comes with several features like no dependencies required, fully customizable via CSS, simple API, no extra files to download, create with UX in mind.

3. Glio.js

https://school.codequs.com/p/HJqC6dN_

glio.js is a javascript library that detects if the mouse of a user leaves the viewport/document borders of your website and when this happens, trigger your callback. Glio increase your conversion rates, gives visitors reason to stay and grabs user’s attention.

4. WebGazer.js

https://school.codequs.com/p/HJqC6dN_

WebGazer.js is an eye tracking library that uses common webcams to infer the eye-gaze locations of web visitors on a page in real time. WebGazer.js is written entirely in JavaScript and with only a few lines of code can be integrated in any website that wishes to better understand their visitors and transform their user experience.

5. Barba.js

https://school.codequs.com/p/HJqC6dN_

barba.js is a small, flexible and dependency free library that helps you creating fluid and smooth transitions between your website’s pages.
It helps reducing the delay between your pages, minimizing browser HTTP requests and enhancing your user’s web experience.

6. Validator.js

https://school.codequs.com/p/HJqC6dN_

validator.js is a library of string validators and sanitizers. It can be used both on client side and server side.

7. Microlight.js

https://school.codequs.com/p/HJqC6dN_

microlight.js is a micro-library which improves readability of code snippets by highlighting, for any programming language, yet without attaching additional language packages or styles.

8. Pilpil

https://school.codequs.com/p/HJqC6dN_

Pilpil is a tiny, pure JavaScript library for Progressive Image Loading with a blur effect to reduce the page load time; as seen on Medium.

9. isMobile

https://school.codequs.com/p/HJqC6dN_

isMobile is a simple javascript library that detects mobile devices. sMobile runs quickly during initial page load to detect mobile devices; it then creates a JavaScript object with the results.

10. AlloyFinger


AlloyFinger is a super tiny size multi-touch gestures library for the web. This content is released under the MIT License.

11. Trial.js


Trial.js is a simple library to monitor mouse position and predict user input. Trial.js has handy features such as no dependency, lightweight, and automatically extends jQuery and Zepto properties.

12. Push.js

https://school.codequs.com/p/HJqC6dN_


Push.js is a compact, cross-browser solution for using the JavaScript Notifications API. Notification API allows modern browsers such as Chrome, Safari, Firefox, and IE 9+ to push notifications to a user’s desktop. Push acts as a cross-browser solution to this API, falling back to use older implementations if the user’s browser does not support the new API.

13. Bideo.js

https://school.codequs.com/p/HJqC6dN_

Bideo.js is a JavaScript library that makes it super easy to add fullscreen background videos. Video might take a few seconds to load, especially because the sources are added via JS which is something you’ll load after the DOM’s loading. Till then you may want to show a video cover which’ll be same as the first frame or the video (or some other image).

14. Ally.js

https://school.codequs.com/p/HJqC6dN_

Ally.js is a JavaScript library that simplifies particular accessibility functions, features, and behaviours. It provides certain standard functions so that JavaScript applications can be made accessible more easily. ally.js has been tested on IE9+, Firefox, Chrome and Safari 9, as well as Mobile Chrome on Android 5.1 and Safari for iOS 9.

15. Tongue.js

https://school.codequs.com/p/HJqC6dN_

“Tongue.js” transforms JavaScript code into any spoken language and comes with a predefined dictionary currently supporting Hindi, Chinese (Simplified). It provides an option to add custom dictionary of words. It creates a experimental platform to create resources to teach people programming who are not comfortable with English, in their mother tongue .
Written by: Gavin 
For more information , please support and follow us. 
Suggest for you:

JavaScript for Absolute Beginners

JavaScript for Beginners

JavaScript Bootcamp - 2016

ES6 Javascript: The Complete Developer's Guide

Upgrade your JavaScript to ES6



Building multiplayer games with Angular_part 3 (end)

Adding the game to Angular

As we’ve already looked at, the game itself will be contained in the <canvas> DOM element. Considering we’re building an angular app, this should be obvious that we’ll need to build a directive.
/scripts/game/game_canvas.js. We’ll create the directive on the angular app.game module.
  1. angular.module('app.game')
  2. .directive('gameCanvas', function() {
  3.   // Build our directive here
  4. });
The directive is pretty bare. Let’s actually create the base directive:

5
6
7
8
9
10
11
12
13
14
15
angular.module('app.game')
.directive('gameCanvas', function($injector) {
  var linkFn = function(scope, ele, attrs) {
    // link Function
  };
  return {
    scope: {
      players: '=',
      mapId: '='
    },
    template: '<div id="gameCanvas"></div>',
    link: linkFn
  }
});

The directive itself is pretty straightforward. We’re creating an isolate scope (as we should always do when building an angular directive) that looks for current players and the map id. We won’t use the players here, but we will use the mapId. We’ve given it a single DOM element in the template to add to the page with an id attribute. Finally, we create a link function where we’ll define the functionality of our directive.
If you’re not familiar with how directives work, check out our post on building custom directives or check out ng-book for a complete book on Angular including how to build a custom directives.
Let’s get to the linkFn. When the directive is attached to the page, it’s link function will get called. Therefore when we call the directive on the page, the link function will execute. We’ll create our phaser game inside this link function.

Let’s create the game in it’s own file at /scripts/game/main.js. Inside this file, let’s create a single function we’ll call where we want to create the function. So as to not place anything on the global window object, we’d likely export the function using CommonJS, AMD, or ES6 (as we do in the full source on github). For simplicity, we’ll place the method on the window object for sake of discussion. See the source code at the end of the article for the more advisable.
  1. // In /scripts/game/main.js
  2. window.createGame = function(scope, players, mapId, injector) {
  3.   // Create our phaser game
  4. };
In this function, we’re expecting a four parameters:

  • The scope of the directive (not strictly necessary)
  • The players variable from the isolate directive definition
  • The mapId from the isolate directive definition
  • The angular $injector

We’re passing the $injector into the function so that anywhere in the game, we can reach out into angular and grab any angular services as needed.

Before we get to building our game, we’ll need to load this in the index.html as well as call the function inside our directive. First, let’s add this as a script tag in our index.html:
  1. <!-- ... -->
  2. <script type="text/javascript" src="scripts/ng-game.js"></script>
  3. <script type="text/javascript" src="scripts/menu/index.js"></script>
  4. <script type="text/javascript" src="scripts/menu/menu_controller.js">
  5. </script>
  6. <script type="text/javascript" src="scripts/game/index.js"></script>
  7. <script type="text/javascript" src="scripts/game/game_controller.js">
  8. </script>
  9. <script type="text/javascript" src="scripts/game/main.js"></script>
Secondly, we’ll call the function in the link function of our directive:
  1. angular.module('app.game')
  2. .directive('gameCanvas', function($injector) {
  3.   var linkFn = function(scope, ele, attrs) {
  4.     createGame(scope, scope.players, scope.mapId, $injector);
  5.   };
  6.  
  7.   return {
  8.     scope: {
  9.       players: '=',
  10.     mapId: '='
  11.     },
  12.     template: '<div id="gameCanvas"></div>',
  13.     link: linkFn
  14.   }
  15. });
With that, we can create our game. Now, using the phaser object from above we can create any game we’re interested in. One nice component of building our phaser game in this way is that we know the directive id. We’ve set it in the template as gameCanvas. So when we build our phaser game, we can depend upon that element being on the page:
  1. // In /scripts/game/main.js
  2. window.createGame = function(scope, players, mapId, injector) {
  3.     // Build the game object
  4.   var height  = parseInt(ele.css('height'), 10),
  5.       width   = parseInt(ele.css('width'), 10);
  6.   var game = new Phaser.Game(width, height, Phaser.AUTO,
  7. 'gameCanvas');
  8. };
Now note that we grabbed the css height and width on the directive. We can dynamically set the height and the width. With that, we can get to building our game. We won’t be building the full game here, as the source is on github (see the end of the article) but for reference the main.js file will look something like:

  1. // In /scripts/game/main.js
  2. window.createGame = function(scope, players, mapId,
  3. injector) {
  4.     // Build the game object
  5.   var height  = parseInt(ele.css('height'), 10),
  6.      width   = parseInt(ele.css('width'), 10);
  7.   var game = new Phaser.Game(width, height, Phaser.AUTO,
  8. 'gameCanvas');
  9.  
  10.     // Load our custom Game object
  11.  var Game      = require('./states'),
  12.       states    = Game.States;
  13.  
  14.   // Add our game states
  15.   game.state.add('Boot', states.Boot);
  16.   game.state.add('Preloader', states.Preloader);
  17.   game.state.add('MainMenu', states.MainMenu);
  18.   game.state.add('Play', states.Play);
  19.  
  20.   // Start the game
  21.   game.state.start('Boot');
  22. };

Cleaning up

Since we’re using a directive, our <canvas> element will hang around on the page for the duration of the angular app. If we navigate away from our game, we’ll want to make sure that we remove the game and all of the memory that it takes up. If the game isn’t running, there is no reason we should be taking up memory to run it.

Since we’re using a directive with a scope, we can listen for the scope’s $destroy event to get fired to know when the directive is getting ready to clean up. When angular is cleaning up a scope, it will emit the event $destroy. We’ll simply call destroy() on the phaser game object and let phaser handle releasing the memory and associated objects.
  1. scope.$on('$destroy', function() {
  2.   game.destroy(); // Clean up the game when we leave this scope
  3. });
Why the $injector?

One method of communicating from the game to angular and visa versa is to use the scope events sytem. For instance, if we wanted to toggle the music of the game from an angular button in the angular app, we could do so by listening for an event fired from angular.

  1. // In /scripts/game/main.js
  2. window.createGame = function(scope, players, mapId, injector) {
  3.   // Set up the game
  4.   scope.$on('game:toggleMusic', function() {
  5.     Game.toggleMusic(); // some function that toggles the music
  6.   });
  7. };

Additionally, we can emit events for angular to listen. If we have a new player or an event from the game we want to project up into angular, we can use the $emit function on the scope object.

Server-side (going multiplayer)

Let’s go ahead and look at how to get the game multiplayer. In this post, we’ll use node and express to create server. In order to run the multiplayer server, we’ll need a few dependencies. We can install them with npm (the node package manager):
1
2
$ npm init
$ npm install --save express lodash socket.io
Since this isn’t a node tutorial, here’s the full server.js file. There are two important pieces to note:

We’re using express.static to serve the angular app
We’re loading a file with our socket.io routes to handle the routing
  1. var express = require('express');
  2. var app = express();
  3. var server = require('http').Server(app);
  4. var io = require('socket.io')(server);
  5.  
  6. // Start the server
  7. var port = process.env.PORT || 8000;
  8. server.listen(port, function() {
  9.   console.log("Running on port ", port);
  10. });
  11.  
  12. // Serve the client
  13. var staticPath = path.join(__dirname, '../client/dist');
  14. app.use(express.static(staticPath);
  15. app.get('/', function(req, res) {
  16.   res.sendfile(__dirname + '/public/index.html');
  17. });
  18.  
  19. // Handle socket.io
  20. require('./routes/io.js')(app, io);
In our /routes/io.js file, we’ll set up some events for our client to fire and interact with the server-side view of our game. Everytime that a player connects, we’ll assume this is a new potential player. That is, we’ll keep track of all the people that are connecting as well as keep track of the ones that are in a game or not.

Setting up our io.js file, it will look like:

2
3
4
5
6
7
8
9
10
11
// routes/io.js
module.exports = (function(app, io) {
 // Game data
  var g = {
    io: io,
    players: [],
    maps: {}
  };
});

Now, when a client connects, we’ll create a new Player object and store their id.

The Player class can be found on github here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// routes/io.js
module.exports = (function(app, io) {
   // Game data
  var g = {
    io: io,
    players: [],
    maps: {}
  };
  g.io.sockets.on('connection', function onConnection(socket) {
    socket.emit('connected', { id: socket.id });
    var player = new Player({ id: socket.id });
    g.players.push(player);
  });
});

Now that we have a player, let’s set up some events for the socket to listen and handle:
  1. // routes/io.js
  2. module.exports = (function(app, io) {
  3.   // Game data
  4.   var g = {    io: io,
  5.     players: [],
  6.     maps: {}
  7.  };
  8.   g.io.sockets.on('connection', function
  9. onConnection(socket) {
  10.     socket.emit('connected', { id: socket.id });
  11.     var player = new Player({ id: socket.id });
  12.     g.players.push(player);
  13.     socket.on('newPlayer', onNewPlayer);
  14.   });
  15.   var onNewPlayer = function(data) {
  16.     // newPlayer event was fired
  17.   };
  18. });
Essentially, we’ve created a newPlayer handler that will handle adding the new player to our player’s array. In order for this event to get fired, we’ll need the client to tell the server there is a new player.

When the game boots up, we’ll have our client send a newPlayer event. For instance:

2
3
4
clientSocket.emit('newPlayer', {
  mapId: Game.mapId,
  health: hero.health
});

Back on the server, we’ll need to do a few things:

Check to see if the map exists or not (create it if not)
Add the player to the players array of the current map
Tell all of the existing players of the new player
Tell the new player about all the existing players
This might sound complex, but it’s pretty simple.

One step at a time, we can check to see if the map exists simply:

2
3
4
5
6
7
8
9
10
var onNewPlayer = function(data) {
  // this.id is the socket id handling the event
  // playerbyId is a helper function
  var player = playerById(this.id);
  // Create the map if it doesn't already exist
  if (!g.maps[data.mapId]) {
    g.maps[data.mapId] = new Map({id: data.mapId});
  }
};

Next, let’s add the player to the map:
  1. var onNewPlayer = function(data) {
  2.   // this.id is the socket id handling the event
  3.   // playerbyId is a helper function
  4.   var player = playerById(this.id);
  5.  
  6.   // Create the map if it doesn't already exist
  7.   if (!g.maps[data.mapId]) {
  8.     g.maps[data.mapId] = new Map({id: data.mapId});
  9.   }
  10.  
  11.   if (!player.inMap(data.mapId) {
  12.     player.joinMap(g.maps[data.mapId]);
  13.   });
  14. };
Now we can tell all of the current players of the new player

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var onNewPlayer = function(data) {
  // this.id is the socket id handling the event
  // playerbyId is a helper function
  var player = playerById(this.id);
  // Create the map if it doesn't already exist
  if (!g.maps[data.mapId]) {
    g.maps[data.mapId] = new Map({id: data.mapId});
  }
  if (!player.inMap(data.mapId) {
    player.joinMap(g.maps[data.mapId]);
    this.broadcast.to(data.mapId)
      .emit('gameUpdated:add', {
        player: player.serialize(),
        map: data.mapId,
        allPlayers: g.maps[data.mapId].players
      });
  });
};

And finally, let’s tell the new player of the currently playing players:
  1. var onNewPlayer = function(data) {
  2.   // this.id is the socket id handling the event
  3.   // playerbyId is a helper function
  4.   var player = playerById(this.id);
  5.   // Create the map if it doesn't already exist
  6.   if (!g.maps[data.mapId]) {
  7.     g.maps[data.mapId] = new Map({id: data.mapId});
  8.   }
  9.   if (!player.inMap(data.mapId) {
  10.     player.joinMap(g.maps[data.mapId]);
  11.     this.broadcast.to(data.mapId)
  12.       .emit('gameUpdated:add', {
  13.         player: player.serialize(),
  14.         map: data.mapId,
  15.         allPlayers: g.maps[data.mapId].players
  16.       });
  17.     this.join(data.mapId); // join the socket group
  18.    this.emit('gameUpdated:add', {
  19.      map: data.mapId,
  20.      allPlayers: g.maps[data.mapId].players
  21.     });
  22.   });
  23. };
client-side multiplayer
Before we can handle socket.io, we need to tell our client app to load the socket.io client-side file. Since we really like angular’s dependency injection system, we’ll use the same pattern we proposed in our d3 article.

We’ll create two services. The first service is the service that loads socket.io on the page. When we instantiate the service for the first time, this provide will dynamically set the script tag on the body and let the browser load the script. It’s not complex, despite the code being pretty large:

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
angular.module('app.loader', [])
.provider('ioLoader', function() {
  this.scriptUrl = window.location.origin+'
/socket.io/socket.io.js';
  this.$get = function($window, $document, $q) {
    var defer = $q.defer(), scriptUrl = this.scriptUrl;
    return {
      done: function(){
        var onScriptLoad=function(){return
defer.resolve($window.io);};
        if($window.io) { onScriptLoad(); } else {
          var scriptTag = $document[0].createElement('script');
          scriptTag.type = 'text/javascript';
          scriptTag.async = true;
          scriptTag.src = scriptUrl;
          scriptTag.onreadystatechange = function () {
            if (this.readyState === 'complete') {
              onScriptLoad();
            }
          };
          scriptTag.onload = onScriptLoad;
          $document[0].getElementsByTagName('head')[0]
            .appendChild(scriptTag);
        }
        return defer.promise;
      }
    };
  }];
});

Without going too much into detail, this service has a single function called done() that returns a promise. When that promise is resolved, then we can depend upon window.io to be loaded on the page. In order to use the window.io object in our app, we can call this function and use the resolution of the object. In code, that looks like:

2
3
4
5
6
7
angular.module('app.loader', [])
.service('ioSocket', function(ioLoader) {
  ioLoader.done().then(function(io) {
    // ioLoader is injected, so we can
    // expect window.io to be loaded
  })
});

The next service we’ll need to create is the socket handler. Since there is a lot of necessary clean-up that needs to go into using socket.io, we’ll use Brian Ford’s awesome socket library to handle it for us.

First, we’ll need to install it, either by going to github and grabbing the source, or using bower:

$ bower install --save angular-socket-io

Next, we’ll create a service that will wrap the socket connection into it’s own promise and return the socket in the promise resolution. This is also pretty simple and the code is much shorter than the previous service:

2
3
4
5
6
7
8
9
10
11
12
angular.module('app.network', [])
.factory('mySocket', function(ioLoader, $q, socketFactory) {
  var mySocket = $q.defer();
  ioLoader.done().then(function(io) {
    var myIoSocket = io.connect(window.location.hostname);
    var aSock = socketFactory({
      ioSocket: myIoSocket
    });
    mySocket.resolve(aSock);
  });
  return mySocket.promise;
});

To use this service, we can simply inject the dependency as usual into our other angular objects and interact with the connected socket on the promise resolution. For instance:

2
3
4
5
6
7
8
9
10
11
angular.module('someMod')
.service('connected', function(mySocket) {
  mySocket.then(function(socket) {
    socket.on('game:event', function(evt) {
      // Handle this event
    });
    socket.emit('game:otherEvent');
  });
});

Thanks! We love to hear feedback and any contributions. Hope this helps you build your own killer game!
Source: newsletter

If you feel useful for you and for everyone, please share it!
Suggest for you:

Learn Angular 2 Development By Building 10 Apps

Angular 2 and NodeJS - The Practical Guide to MEAN Stack 2.0

Angular 2 - The Complete Guide (Updated to RC4!)

Angular 2 Fundamentals: Learn By Creating A Real Web App

JavaScript Promises: Applications in ES6 and AngularJS