Javascript News

Syndicate content
Pipes Output
Updated: 48 weeks 6 days ago

Streamlining Stock Image Use with Adobe Stock

Mi, 2015-08-19 00:35

This article was sponsored by Adobe. Thank you for supporting the sponsors who make SitePoint possible.

Finding the right stock image can be such a tiresome task; I despise it. I can easily tally up 20 to 30 images and remain indecisive for days, but even when I’ve made a decision I still need to clear it with the client, who might have other ideas.

Back to square one, and also to that awkward folder on my desktop where I have to store all of my other tiny low-quality samples - and that’s even if a stock website offers samples.

Before hearing about Adobe Stock I would save the image to a folder on my hard drive, locate the image using File → Place and import it into the Photoshop document. If it wasn’t suitable after all, I’d have to repeat those steps all over again.

Now, thanks to Adobe Stock, I can work much more speedily by storing all of my stock images in the Creative Cloud. This means I can access my stock images in Photoshop CC, Illustrator CC, InDesign CC, Premiere Pro CC and even After Effects CC. In Photoshop, you can simply drag the images from the Library Panel (which is always in-sync with Creative Cloud) directly to the artboard, there’s no need to manage stock images on your local machine. The library interface is fairly straightforward and the thumbnails are large enough to make multiple iterations a breeze.

In this article we’re going to show off the strengths of Adobe Stock by finding the perfect image for a given design project.

The concept in this case is an article called Time to Hit the Wall Street where the title reads “time to hit the” and the background image has the Wall Street sign in it.

Obviously, there are quite a few images of the Wall Street sign (Adobe Stock has over 40 million curated images in total), but we need a very specific example that allows the article title to run into our background image, because we’re clever like that!

Getting Started

Assuming you have the Photoshop CC 2015 update and the Library Panel is open, click on the “St” icon and Adobe Stock will automatically open in the browser. Log in with your Adobe ID and then search “Wall Street”.

Continue reading %Streamlining Stock Image Use with Adobe Stock%

Microsoft Edge: the Review

Di, 2015-08-18 22:00

Microsoft has been doing the right things for several years. They engage with the community, fix bugs and announce new features in advance (certain less open competitors could learn from their example). IE11 is a good browser -- or was when it was released in 2013. Despite this, IE's historical legacy remains. At best, developers ignore the browser, and market share has been dwindling.

In an effort to move beyond the tainted Internet Explorer brand, Microsoft has released Edge. The new browser is based on the same Trident engine, but the bloat has been removed, rendering speed has increased, and modern HTML5 features have been added. It's a fresh start that consigns ActiveX and VBScript to the technological trash heap.

Edge is the future, but there's only one way to get it …

Install Windows 10

Windows 7, 8 and 8.1 users can either wait for the upgrade or force it using the Windows 10 Media Creation Tool. Few people will have problems, but there have been scare stories. I was one of the unlucky ones, and ended up with an unusable machine for a couple of days. In my experience, the safest options are:

  1. Back-up your data, applications, configuration options and anything else you're terrified to lose. Then back-up again. And verify. You can't be too careful.
  2. Ensure you have a Windows 8 installation DVD to hand. If anything goes wrong, you'll need to re-install or pay Microsoft for a new Windows 10 license.
  3. If you're installing on an SSD, you may need to disable fast boot in the BIOS.
  4. Either wait for the update or choose "Upgrade this PC" from the Media Creation Tool. Installing from the ISO or DVD seems more problematic.
  5. Once Windows 10 has installed, ensure it's activated. This will permit you to install a fresh copy without a Windows 8 upgrade.

This isn't a full review, but Windows 10 is a great OS. It papers over the cracks in Windows 8 and makes the system more desktop-friendly. It'll be familiar to those migrating from any version of Windows, which is a considerable achievement.

A real Start button is back, although the 'All apps' list is more cramped and less usable. Cortana -- Windows' Siri equivalent -- is fun, although she mostly fires a Bing search.

There are a few quirks and inconsistencies. The new Settings panel is an improvement, but the old Control Panel still exists, and you'll often need to switch between the two. Some Metro (or whatever they want to call it) apps weren't designed to operate in smaller, non-full-screen windows, which can cause issues. But many problems should be resolved over the coming months. The majority of people will like Windows 10 … but will they like Edge?

Continue reading %Microsoft Edge: the Review%

The Advanced Guide to Facebook Graph Search

Di, 2015-08-18 19:25

In 2013, Facebook rolled out Graph Search, a powerful semantic search engine that granted users more control over Facebook’s ever-expanding universe of big data. Over the past several months, however, Facebook has begun to scale back Graph Search’s capabilities – a setback for many businesses which have come to rely on the service to gather […]

Continue reading %The Advanced Guide to Facebook Graph Search%

An Introduction to b2evolution

Di, 2015-08-18 19:00

If you were going to set up a new business, selling and supporting a range of on-line training courses for example, but wanting to keep costs down, there’s a good chance you’d start to look at self-hosted Open Source offerings. You’d need to be able to run a number of static pages, some dynamic content to handle your courses, perhaps a forum to interact with your customers, they’d need some kind of user management, and a maybe a messaging service to handle marketing. Already I can hear you thinking that’s several different products you’ll need, and an integration headache to go along with it. So if I then told you there’s already something out there that does all that, securely, and can be deployed in a matter of minutes; you’d be interested, right? Of course you would...

But first let’s take a little trip back in time.

A Short History Lesson

Back in 2002, Francois Planque, switched to b2 as an alternative to Blogger’s infamous bugs - he liked what he saw. However within a few months, its maintainer and a much anticipated new release faded from view. As Francois put it, “the b2 project started looking like a dead end”. Not wanting to switch over to yet another blogging tool, he decided to build on his existing programming and DBMS skills, and learn the specifics of PHP & MySQL, to see whether he could add the features he felt b2 needed; in particular the ability to run multi-blogs from the same installation.

Finding he was enjoying the experience, within weeks, Francois was thinking of releasing, what he had called b2evolution, publicly. Unbeknown to him though, someone else had had the same idea and was also working away on the b2 code. The stars aligned to see both new releases coming out in the same week, and a few weeks later b2’s original maintainer re-appeared and announced that b2evo’s rival would become the official successor.

Whilst he was invited to merge his work back into the ‘official release’, Francois ultimately decided he liked the way in which his own branch was developing, and so the journey continues to where b2evolution has reached today.

And the ‘official branch’? Oh yeah, you might have heard of it, they called that WordPress.

Main Features

Up until June 2015, the 5.2.2 stable release was the one on show for potential users to download, though those who had registered with the site were also able to give the new 6.4.x beta versions a go and feedback on what was in the offering.

Continue reading %An Introduction to b2evolution%

Using Jade and Grunt to Speed Up HTML Production

Di, 2015-08-18 18:00

Whenever we talk about building a web application, we need to talk about language preprocessors (transforming source code written in a particular language to target code in a native language). Often you’ll find yourself using languages that aren’t natively supported by web browsers because they help you wrap away repetitive work by providing features not available in plain HTML (e.g. Jade), CSS (e.g. Sass) and JavaScript (e.g. CoffeeScript).

An HTML template engine is a preprocessor that gives us the ability to write dynamic and reusable HTML documents that follows the ( DRY ) principle of application design.

Jade is an open source HTML templating language for Node.js (server-side JavaScript). Jade is totally free to use and provides fast, easy, and fun HTML. It is heavily influenced by Haml, and it was originally created in Node as a module. It typically includes features common to most high-level programming languages, with an emphasis on processing plain text.

When using modern CSS frameworks like Bootstrap and Foundation, most of the development becomes entirely about producing HTML, which brings out the power of Jade. Once you start using it, it’ll become an indispensable tool for you.

In this tutorial I am going to introduce how to accelerate HTML production and inject plain data with Jade features in conjunction with Grunt.

Our toolset for this tutorial will include:

  • Jade
  • Grunt
  • NodeJS
Preparing the Environment: Installation

Here are the steps for installing Node.js, Jade, and the Grunt command-line interface (CLI). If you already have these installed, you can skip down to the next section in the tutorial.

  1. Go to nodejs.org, and click on the “Install” button to download the latest version of node. Execute the downloaded file and follow the installation instructions.

  2. npm (Node Package Manager) will come bundled with Node, and can be used via the terminal. Open your terminal and execute npm init in the project directory. Then follow the instructions to create package.json.

  3. To install Grunt, enter npm install --save-dev grunt
  4. Install the Grunt CLI (command-line interface) npm install -g grunt-cli to execute tasks straight from the command line.
  5. To install the Grunt plugin for Jade tasks, type npm install --save-dev grunt-contrib-jade
  6. To install Jade, type npm install --save-dev jade

NOTE:: There are three flags for installing npm packages:

  1. --save means those packages are required locally for the project and listed under the dependencies property.
  2. --save-dev adds the packages locally but as development dependencies. They are listed under devDependencies in package.json.
  3. -g indicates the package should be installed globally; this lets you execute grunt in your terminal, regardless of the current working directory.

A package.json manifest file will be created, which indicates a list of packages the project depends upon, and it includes some meta data such as project name, version, and description.

After the installation your package.json manifest will look like the following:

[code language="javascript"]
{
"name": "jadeTutorial",
"version": "1.0.0",
"description": "Jade with Grunt tutorial",
"main": "index.js",
"author": "Nouran Mahmoud",
"license": "ISC",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-jade": "^0.14.1",
"jade": "^1.9.2",
}
}
[/code]

In addition, a node_modules directory will be created and will include the npm modules installed earlier as grunt and jade.

What is Grunt?

I’ll introduce you to Grunt, a popular task runner, we will use it to automate and execute time-consuming command line tasks in your development workflow. A task is an action that produces a target like compiling Jade to generate HTML. Using Grunt, we will be able to run Jade, watch tasks, and perform any other task with only one command line. It’s okay if you’ve never heard of a task runner before; it’s not a hard concept to wrap your head around.

Grunt is not the absolute best tool for this job. If you are curious about using other build tools, you can check out these resources: How to Use npm as a Build Tool or An Introduction to Gulp.js.

Continue reading %Using Jade and Grunt to Speed Up HTML Production%

Video: Getting to Know Block Statements in JavaScript

Di, 2015-08-18 17:30

In this lesson, you will learn about how JavaScript lets you group statements, and why that can be useful. You will be introduced to the syntax of statement groups, and get an overview of how statement groups can be used for conditional logic as well as for control flow. This is only one small section of a course that takes beginners from simple variables and types all the way through the fundamentals of functions and scope in JavaScript.

My course Introduction to Programming With JavaScript was designed for people who may never have coded, or may have copied and pasted other people's scripts into a web page without really understanding how they worked. It's a good general introduction to the concepts of programming in JavaScript, and the features of the language.

If you like what you see here, and want to learn more, please sign up for SitePoint Premium to gain access to the entire course.

Loading the player...

Continue reading %Video: Getting to Know Block Statements in JavaScript%

10 Essential Material Design Resources and Tutorials

Di, 2015-08-18 17:00

When Google announced Material Design, it caused a splash in the Android community and beyond. It's been a Long Road to Google's Material Design, but the journey has been worth it.

Material Design is no longer new, but it's as popular as it was on launch day. Material Design has a lot of good resources, but if you are new to the concepts, you are probably wondering where to begin.

The most logical (but not the easiest) place to start, is the Material Design specification itself.

Continue reading %10 Essential Material Design Resources and Tutorials%

Sample Project: Use Famo.us and Angular to Create a Mobile Application

Di, 2015-08-18 16:30

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

I love high-performance JavaScript and I love sharing what I believe is its true potential. In this tutorial, I want to focus on Famo.us – it can allow you to maintain a silky smooth 60 frames per second while having fluid animations on screen. Famo.us does this by utilizing the CSS3 primitive -webkit-transform: matrix3d, which lets the framework compute the composite matrix and skip the browser’s renderer. No plug-in, no download, no hack. By appending this to each DIV, developers can render the composite matrix and go straight to the GPU.

I go more in depth when discussing the ins-and-outs of Famo.us in this blog post. Thanks again to Zack Brown for all of your assistance with this! Let’s get started:

By the end of this project you will be able to:

  • Understand how Angular works within the context of a Famo.us application
  • Harness the true power of JavaScript and the good parts of HTML5
  • Create smooth animations

My goal for this project to illustrate how easily you can create HTML5 / JS projects which work at near native speeds on mobile applications.

Features
  • The mobile applications runs on iOS and Android via Cordova
  • The Windows 10 universal app runs natively on well, Windows 10
  • This project can also be run as a hosted website, although I have it scaled best for mobile devices
Requirements
  • PC or Mac
  • Web server
  • Cross-platform test matrix (like a BrowserStack, IDE, or free virtual machines for EdgeHTML, the rendering engine for Microsoft Edge and hosted web app content on Windows 10).
Setup
  1. 1.Download the source from GitHub
  2. 2.Download & install a web server (I use MAMP on OS X, or the built-in IIS server with Visual Studio on Windows)
Opening the project
  1. 1.Start your web server
  2. 2.Navigate to famous-angular-Pokemon/app/

The project is designed to work on mobile devices, so use the mobile emulator in your browser to get the correct view. Here’s what it would look like on an iPhone 6 inside the emulator via the Chrome desktop browser (375x667):

How it works Hitting the database

I pull all of the information from the PokeAPI, which has a well-documented API, but it’s missing images for each of the Pokémon. For the images, I just pull the name of the currently chosen pokemon and appending it to the end of this URL: http://img.pokemondb.net/artwork/. For example: http://img.pokemondb.net/artwork/venusaur.jpg will lead you to an image of Vanosaur. Nifty, right? Sadly, they do not have an API available.

Each time the user presses the Next button, a random number is generated between a min / max value that I’ve defined (say, 1-20), and it pulls a Pokémon from the database which matches that number. Here’s what it looks like:

http://pokeapi.co/api/v1/pokemon/1/ returns a JSON object for Bulbasaur. You can play with their API here.

Continue reading %Sample Project: Use Famo.us and Angular to Create a Mobile Application%

5 Easy Performance Tweaks for Node.js Express

Mo, 2015-08-17 20:00

Node.js has revolutionized web development and the Express framework must share much of the credit. Express may not be the fastest or most advanced server option, but it's almost certainly the most-used with more than 3 million downloads per month.

If you do nothing, Node.js and Express run blazingly fast. However, there are a number of simple ways to make Express 4.x run even faster…

1. Switch to Production Mode

Express can run in several modes. By default, it presumes development mode which provides exception stack traces and other logging tasks. There is also a debugging mode which logs messages to the console, e.g.

[code]
DEBUG=express:* node ./app.js
[/code]

On your live server, you can noticeably improve performance by switching to production mode. This is achieved by setting the NODE_ENV environment variable to production. It can be set in the current session on Windows prior to launching your Express application:

[code]
set NODE_ENV=production
[/code]

or Mac/Linux:

[code]
export NODE_ENV=production
[/code]

Linux users can also set NODE_ENV in a single line when launching:

[code]
NODE_ENV=production node ./app.js
[/code]

Ideally, you should configure your environment by adding export NODE_ENV=production to your ~/.bash_profile or appropriate start-up script.

2. Enable GZIP

Express 4.x provides minimal functionality which can be enhanced with middleware. One of the less obvious missing features is GZIP compression which shrinks the HTTP payload so it can be expanded by the browser on receipt. To add GZIP, install the compression module using npm:

[code]
npm install compression --save
[/code]

(Depending on your setup, you may need to use sudo on Mac/Linux -- there are various ways to fix that.)

In your main application launch file, include the compression module:

[code language="javascript"]
var compression = require('compression');
[/code]

then mount it as the first middleware function (prior to other Express .use methods):

[code language="javascript"]
// GZIP all assets
app.use(compression());
[/code]

Continue reading %5 Easy Performance Tweaks for Node.js Express%

Visualizing a Twitter Stream in VR with Three.js and Node

Mo, 2015-08-17 18:00

Twitter is a wonderful and information rich beast. I wanted to combine some of the powers of visualization, Three.js and its VR capabilities with Socket.IO and Node to create a pretty world of particles generated via a Twitter stream.

I've previously discussed all the basics of developing virtual reality web experiences in the SitePoint article Bringing VR to the Web with Google Cardboard and Three.js, so if you are new to this whole idea - read that one first and come back. This demo uses the same foundations.

The demo we will be building will watch a live Twitter stream for a keyword. When one is tweeted out whilst it is watching the stream, it will bring up a "tower" of shining particles that represent how long the tweet was. This demo in particular will look for mentions of the word "pizza". Why pizza you ask? I was looking for a term which was not mentioned as frequently as "bieber" but more frequently than "boxcar racing hyenas". In short, the best terms are ones which are relatively frequent enough that they'll appear whilst you are watching, but not so frequent that they come through at many hundreds a second. Pizza is one of them.

Demo Code

If you're keen to get straight into the code and try it out, you can find it here on GitHub.

Want to try it in action? I've got a running version hosted here: VR Twitter World.

Our Server Code

We'll begin by looking at our Node server code. It will display our flat HTML and also operate as a Socket.IO server that'll pull in a stream of data from Twitter.

The full server is relatively short and looks like so:

[code language="js"]
var express = require('express'),
app = express(),
server = require('http').createServer(app),
port = process.env.PORT || 80,
io = require('socket.io')(server),
config = require('./config.json'),
Twitter = require('node-tweet-stream'),
t = new Twitter(config);

app.get('/', function(request, response) {
response.sendFile(__dirname + '/public/index.html');
});

app.get(/^(.+)$/, function(req, res) {
res.sendFile(__dirname + '/public/' + req.params[0]);
});

app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});

server.listen(port, function() {
console.log('Listening on ' + port);
});

t.track('pizza');
t.on('tweet', function(tweet){
console.log('Roger that. Tweets incoming!');
console.log(tweet);

io.emit('tweet', tweet);
});

t.on('error', function (err) {
console.log('Brace yourself! We are goin doooowwwwwwnnnnnnnn! ', err);
});
[/code]

Our first lines set up a server using the Node Express framework. It's a rather simple set up that is pulling in all our dependencies and preparing the app variable for us to access our server functionality. port sets up which port we want our server to run on (process.env.PORT is a server variable some hosting set ups like Heroku will have defined).

[code language="js"]
var express = require('express'),
app = express(),
server = require('http').createServer(app),
port = process.env.PORT || 80,
[/code]

Then we set up the io variable whilst simultaneously starting up our Socket.IO server functionality, attaching it to the Express server we set up above:

[code language="js"]
io = require('socket.io')(server),
[/code]

Setting Up Twitter Access

The config variable is a nice way of keeping the application's Twitter authentication keys and access tokens in their own file. In order to live view the Twitter stream, we will be using an npm module called node-tweet-stream which provides all the functions we will need. We assign the object for our Twitter access and all associated functions to the t variable, passing in our config JSON to prove we're allowed to access it.

[code language="js"]
config = require('./config.json'),
Twitter = require('node-tweet-stream'),
t = new Twitter(config),
[/code]

If you don't have any Twitter keys for access to the Twitter API, never fear! You just need to register an app with Twitter. Head to the Twitter Application Management page, log in with your Twitter credentials and then click "Create New App".

Once you have an app, you can get your keys and access tokens by clicking the "Keys and Access Tokens" link that will appear on your app's management page. If you can't find it, it will be at the URL of: https://apps.twitter.com/app/0000000/keys (replacing 0000000 with your app's ID).

Then, create a file on the same level as index.html called config.json. Within it, add the following with your own app's values:

[code language="js"]
{
"consumer_key": "YOURKEY",
"consumer_secret": "YOURKEYSECRET",
"token": "YOURTOKEN",
"token_secret": "YOURTOKENSECRET"
}
[/code]

Other Server Basics

Further along in our index.js file, we set up calls to the root of our server to load /public/index.html:

[code language="js"]
app.get('/', function(request, response) {
response.sendFile(__dirname + '/public/index.html');
});
[/code]

We also have it serve up any other static files within the public directory on our server:

[code language="js"]
app.get(/^(.+)$/, function(req, res) {
res.sendFile(__dirname + '/public/' + req.params[0]);
});
[/code]

If we do have an error, we log that error in our server's console and return a 500 error:

[code language="js"]
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
[/code]

The following lines start our server running with all the settings above.

[code language="js"]
server.listen(port, function() {
console.log('Listening on ' + port);
});
[/code]

Continue reading %Visualizing a Twitter Stream in VR with Three.js and Node%

Video: Working with Sublime

Mo, 2015-08-17 17:30

Learning the features your editor has to offer is a great way to maximize your productivity. Learning keyboard shortcuts allows you to be fast and precise without having to take your hands off the keyboard. While that looks like a fairly simple thing, it can help you immensely when you are immersed in code. Spending a little amount of time to familiarize yourself with your editor helps in the long run. While most other editors either have a really high learning curve or are heavy and slow to use, Sublime text is easy to get started with.

In this screencast I will show you how to traverse within files and projects, line manipulations and explore Sublime's combination keys.

Loading the player...

Continue reading %Video: Working with Sublime%

From Request to Response: A Journey into Drupal 8 Internals

Mo, 2015-08-17 16:00

In the first article on Drupal 8 module development we looked a bit at the routing aspect of this process. We’ve seen that creating pages with paths is now a matter of declaring routes that match up with controllers. The latter, as we’ve seen, can return a render array that gets interpreted into markup and displayed in the main content area of that page. However, did you know that under the hood, Drupal actually transforms that array into a Response object according to the dictates of Symfony’s HTTPKernelInterface?

In this article, I would like us to go deeper into the internals of Drupal 8 (and Symfony2) and look at what actually happens (and can happen) from the moment a request is made by a user to the one in which they see something returned in response. The example I mentioned above is just one direction this process can go in, and today we are also going to see other possibilities. The goal is to understand the flexibility of the system which in turn can help us build awesome applications.

Before going into it, I strongly recommend you check out this diagram which does an amazing job at synthesizing what is often referred to as the render pipeline. Though in my opinion it represents more than the name implies because the render system is only part of what’s depicted, albeit a big one.

Continue reading %From Request to Response: A Journey into Drupal 8 Internals%

Understanding Scope in Ruby

Mo, 2015-08-17 14:00

Scope is an essential thing to understand, not just in Ruby, but in any programming language. Back in the days when I was starting to write Ruby, more than half of the errors thrown at me were as a result of not understanding this concept well enough. Things like variables not being defined, incorrect variable assignments, and so on. All as a result of not understanding scope well enough. You don't have to go through all of these headaches! This article will hopefully help you avoid many of the mistakes I did.

What is Scope, Exactly?

When someone mentions scope, think of 2 words: variables and visibility.. It's pretty straightforward: Scope is all about where something is visible. It's all about what (variables, constants, methods) is available to you at a given moment. If you understand scope well enough, you should be able to point at any line of your Ruby program and tell which variables are available in that context, and more importantly, which ones are not.

So what's the point of restricting visibility to variables in the first place? Why not have everything available anywhere? Life would be much easier that way, wouldn't it? Well, not really...

There are many things programmers disagree about (using a functional vs. object-oriented approach, using different variable naming templates, etc.). Scope is not one of them. Especially as people get more experience with programming, they are stronger proponents of it. Why is that?

Because the more you work in programming, the more you'll have the chance to experience the horror of having everything available everywhere. Global state makes your program very unpredictable. It's very hard to track who changes what when everyone has the ability to do so. Who wrote to this variable? Who read it? Imagine having ten thousand lines of code and asking these questions for each line!

Then come naming issues. If you have a big program, you'd have to give all of your variables unique names to avoid conflicts. Imagine keeping track of thousands of variable names.

Continue reading %Understanding Scope in Ruby%

The 4 Hardest Lessons for Startups to Learn

So, 2015-08-16 18:45

Google’s restructuring. Zen99’s closed. Zirtual’s disappeared (then reappeared). And Homejoy’s abandoned ship. That’s a lot of bad news for a hungry, starry-eyed entrepreneur, to digest in less than one week. As a bootstrapping founder myself, this scared the crap out of me – until I pulled myself together, did some reading and extrapolated a few […]

Continue reading %The 4 Hardest Lessons for Startups to Learn%

The 18 Best IFTTT Recipes to Skyrocket Productivity

Sa, 2015-08-15 16:00

There’s a lot of creative productivity hacks out there. But as you’ve probably found, most of them are totally impractical. Sure, you could wake up an hour earlier—but then you’re ready for bed an hour earlier as well. Or you could work in 20-minute chunks with 5-minute breaks—but inevitably, those breaks stretch into 8 minutes, […]

Continue reading %The 18 Best IFTTT Recipes to Skyrocket Productivity%

Build a Real-Time Status Update App with AngularJS & Firebase

Fr, 2015-08-14 18:00

If you’ve spent any time with AngularJS then you’ll likely be familiar with Firebase—a realtime data store that makes it very easy to save and sync data across any platform. Firebase provides an AngularJS binding for its platform called AngularFire which makes using the Firebase API even easier.

In this tutorial we will be creating a simple status update app that will let us see how AngularJS and Firebase interact. For the UI, we’ll use Angular Material which is the AngularJS implementation of Google’s Material Design and comes with a large set of great UI components. Angular Material is based on flexbox which might take a bit of getting used to if you haven’t become familiar with it yet. We’re also going to focus a lot on the authentication portion of the app which, as we’ll see, is made simple by Firebase’s built-in authentication system.

This tutorial will assume that you’re familiar with AngularJS and that you have a cursory understanding of what Firebase is and how it works.

As ever, the code for this tutorial can be found on GitHub.

Installing the Dependencies

Let’s start by installing what we’ll need for the app using npm.

From the command line:

mkdir status-app && cd status-app npm install angular-material angular-ui-router angularfire angular-md5

Installing Angular Material will give us other packages as well, including the most recent version of AngularJS. We’ve included UI Router as we’ll need to handle two different states—one for logging in/registering and another for viewing statuses. Angular MD5 will give us a quick way to hash email addresses which will be needed for getting Gravatar images for our users.

You'll also need some kind of server to view and interact with the app. For this purpose http-server is ideal.

Setting up the App

We’ll want a folder structure that gives us a clean way of breaking out the different areas of responsibility. For this, let’s use a folder called components. The entire folder structure should look like this:

status-app |-- components |-- auth |-- status |-- user |-- node_modules * dependencies -- app.js -- index.html -- style.css

Let’s setup our index.html file with references to the dependencies we installed already, as well as the application scripts that we haven’t yet created.

<!-- index.html --> <!DOCTYPE html> <html> <head> <title>Status App</title> <link rel="stylesheet" href="node_modules/angular-material/angular-material.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body ng-app="statusApp"> <div layout="row"> <div flex="33" offset="33"> <div ui-view></div> </div> </div> </body> <!-- Application Dependencies --> <script src="node_modules/angular/angular.js"></script> <script src="node_modules/angular-ui-router/build/angular-ui-router.js"></script> <script src="node_modules/angular-material/angular-material.js"></script> <script src="node_modules/angular-animate/angular-animate.js"></script> <script src="node_modules/angular-aria/angular-aria.js"></script> <script src="https://cdn.firebase.com/js/client/2.2.6/firebase.js"></script> <script src="node_modules/angularfire/dist/angularfire.js"></script> <script src="node_modules/angular-md5/angular-md5.js"></script> <!-- Application Scripts --> <script src="app.js"></script> <script src="components/auth/authController.js"></script> <script src="components/auth/authService.js"></script> <script src="components/status/statusController.js"></script> <script src="components/status/statusService.js"></script> <script src="components/user/userService.js"></script> </html>

We’ve bootstrapped the app on the body tag and called it statusApp. We’re also immediately making use of Angular Material in the body by specifying that the opening div tag should have a layout of row. By setting the layout to row, everything inside the container will be placed horizontally. If we were to set the layout to column, everything would be stacked vertically.

In the next div, we’re setting the width to be 33% by putting a value of 33 on the flex attribute. The offset attribute lets us center the element by saying it should be moved over to the right by a third.

The last element is our ui-view tag which is the point at which our (yet to be created) UI Router states will be loaded.

We’ll also need an app.js file to get the application started.

// app.js (function() { 'use strict'; angular .module('statusApp', ['firebase', 'ngMaterial', 'angular-md5', 'ui.router']) .config(function($stateProvider, $urlRouterProvider) { // If a route other than status is requested, // go to the auth route $urlRouterProvider.otherwise('/auth'); $stateProvider .state('auth', { url: '/auth', templateUrl: 'components/auth/authView.html', controller: 'AuthController as auth' }) .state('status', { url: '/status', templateUrl: 'components/status/statusView.html', controller: 'StatusController as status' }); }); })();

As you’ll see, we’re calling the AngularJS module statusApp which matches up with our ng-app declaration on the body tag. We’ve injected the modules we need by specifying them in the array next to the module name and then setup some configuration for the app. The configuration block is where we’ll setup the rules for UI Router to handle our different states. To make this happen we need to pass the configuration function $stateProvider and $urlRouterProvider.

We’ve yet to setup the actual controllers and templates for these states, but what we’re saying here is that when we are at a URI of /auth, we want to load the auth view and auth controller. This state is responsible for providing a login and registration box for users.

Once logged in, we want to go to the /status state which loads the status controller and view. Finally, we want to negate any other routes so we tell $urlRouterProvider if in doubt, send the user to the /auth state.

A Little CSS

We’ll need a little bit of CSS to style the status listings in our app.

/* style.css */ .face { border-radius: 30px; border: 1px solid #ddd; width: 48px; margin: 16px; } .remove-status { cursor: pointer; color: red; font-weight: bold; } Handling Authentication

Our app is going to need to be able to register and authenticate users and fortunately for us, Firebase provides an easy to use, hosted solution for authentication. While it offers ways to authenticate with Google, Facebook and others, we’re going to keep things simple by relying on their email and password method.

NOTE: The code samples reference my own Firebase app that I’ve created which you are free to use. Alternatively, you may create your own Firebase account and change up the references to in the code to point to it. To do so, see the section Adding Your Own Firebase Account at the end of the article.

First, let’s create an authentication service.

// components/auth/authService.js (function() { 'use strict'; angular .module('statusApp') .factory('Auth', AuthService); function AuthService($firebaseAuth) { var ref = new Firebase("https://statusapp.firebaseio.com"); return $firebaseAuth(ref); } })();

We give this factory a name of Auth and setup a connection to the already-created Firebase app called statusapp. We pass our application reference to $firebaseAuth which is the service responsible for handling the Firebase authentication methods. Returning this from our Auth service will allow us to hook into it from our controller.

Next, let’s setup the authentication controller with some methods that will login and register users.

Continue reading %Build a Real-Time Status Update App with AngularJS & Firebase%

Spicing up Your Emails with Markdown

Fr, 2015-08-14 17:00

Markdown provides a simple way to mark up plain text so that it can be converted to HTML.

I use Markdown daily to write documents, website content and so on. I also compose a lot of emails, so I was delighted to stumble on an easy way to create pretty HTML emails with Markdown too.

Markdown Here

Markdown Here (MDH) is a simple browser extension that can be installed in browsers such as Chrome, Firefox, Safari and Opera. It adds an icon to your browser's address bar:

Simply add Markdown syntax to your email, and when you're ready to send, click the MDH icon. (You can also activate MDH via a keyboard shortcut of your choice—CTRL + ALT + M by default—or a via a dropdown context menu.)

For example, you can send emails that look like this:

Other Uses

If sending email in the browser isn't your thing, you can also use MDH with email clients such as Thunderbird, Postbox and Icedove.

And Markdown Here isn't limited to email. You can use it in other web editing interfaces such as Google Groups, Evernote and WordPress.

Creating HTML Emails

I tend to send email directly through Gmail in my browser. It's really nice to be able to enhance emails with some HTML formatting, which is easy with Markdown.

I often need to send longish emails, and it's great to be able to add headings, quotes, inline code, code blocks and lists to make the email readable and break up the content.

Here are some examples of what you can do.

Code

Being involved in web design and development, I often send code samples in emails.

Writing inline code is as easy at this:

You could try `.element {display: block;}` instead.

After the MDH conversion, the above text look like this:

And a block of code is easy too. Note that you can specify the language to get nice syntax highlighting:

```javascript (function() { var method; var noop = function () {}; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log' ]; var length = methods.length; var console = (window.console = window.console || {}); }()); // From the HTML5 Boilerplate ```

And this is the result:

Continue reading %Spicing up Your Emails with Markdown%

Using Sphinx for PHP Project Documentation

Fr, 2015-08-14 16:00

I recently had the need to write proper prose-like source-code documentation for the Diffbot PHP client. Having looked at several documentation generators, and even having suggested a @prose tag for importing of related MD/reST documents into method and class descriptions, I realized there simply is no perfect solution we can all agree on (yet). So until I extend Sage with a @prose token and reST parsing, I opted for ReadTheDocs and Sphinx.

RTD is widely used in the industry. It hosts powerful docs such as Guzzle’s, PhpSpec’s and many more. It supports reST alongside MD (or, to be more accurate, MD alongside reST), which is a huge plus as RST files are more suitable for highly technical documents. It can be run locally and generate offline-friendly HTML files, but it can also compile from documentation source available online and and be automatically hosted as a subdomain of readthedocs.org.

That said, setting it up for a PHP project has some caveats, so we’ll go through a basic guide in this tutorial.

TL;DR

If you’re just looking for the list of commands to get up and running quickly:

Continue reading %Using Sphinx for PHP Project Documentation%

Eyetracking: How to Watch the Gap Between the Clicks (and Why)

Fr, 2015-08-14 15:30

Information overload is becoming an epidemic for web users across the globe. When users visit your website or use your app, you only have a few seconds before users decide to stay or bounce.

Traditional analytics can be useful for getting a macro overview of your site metrics, however when you're building out a new design or making changes, you need a way to get inside the mind of your users.

Many web development professionals turn to heatmaps and mouse tracking for detailed insights as it's a relatively simple way to gather insights about your website. For those times you need to take your research to the next level, eyetracking (also known as gaze interaction) is the tool for you.

Eyetracking is Hard. Why Bother? Complex Projects

Travel websites are a perfect eye tracking use case because of the website complexities. Airfare in particular is a great fit for this tool because customers have an endless amount of possibilities for planning their trip.

As shown by a video from Matchic Labs Eye Tracking, there's plenty of activity which occurs without the measurable click of a mouse or tap of a screen. If you're handling a project with a complex interface or situations where users need to process large amounts of information, eye tracking is essential for your success.

E-Commerce

While heatmaps and mouse-tracking are viable solutions for most e-Commerce settings, there are times where companies need to take their research to the next level. As Rick Nguyen, the founder of ad testing firm Spot Trender pointed out in an interview.

While eyetracking be can be more expensive than traditional UX testing methods, like click tracking or mouse tracking, eyetracking can significantly improve your sales. For instance, if you have a site selling hats, you would probably want users to focus on the hat rather than the shirt the model is wearing.

Online Advertising

Advertising is all about invoking an emotional reaction from the viewer. As with eCommerce, eyetracking enables you to to see how users are reacting to your banners or video ads.


Image source: http://media.nngroup.com/media/editor/alertbox/banner-blindness-examples.jpg

Bidding on competitive keywords can easily burn a hole in your wallet. Bidding on niche keywords can help to reduce your burn rates, but unless you have data on user reactions, you'll be following the "spray and pray" method of video production.

Is DIY Eyetracking an Option?

While this technology might seem limited to companies with six figure budgets (the equipment alone can cost $9,000-$20,000 upwards), you can integrate eyetracking into your projects for as little as a couple hundred dollars.

If you're willing to get your hands dirty, you can always DIY an eyetracking solution for a couple hundred dollars.

[caption id="attachment_112628" align="aligncenter" width="620"] Instructables: A DIY eyetracking solution (link). [/caption]

To gather insights around your projects, PyGaze is worth exploring. For Python developers, the system should be fairly easy to implement. Be warned that if you aren't a developer, or if you don't have one on hand, then this solution isn't for you. PyGaze is a complex tool which has a low price point (free), however it requires hours to setup.

If you're looking to immediately get started with eyetracking, Gazepoint offers a variety of solutions to fit a variety of needs.

Best Practices Determining Your Sample Size

As with any usability testing, you need to ensure that you're surveying enough users for accurate results. You can figure out a precise amount using the Holm-Bonferroni method, however it's a bit difficult to grasp unless you're a statistician. When doing your tests, you should aim for 95% accuracy. If you have a smaller budget or less time for testing, you can get away with as little as 80% accuracy.

If you want to spare yourself from headaches, you can always use a sample size calculator to determine the amount of people you should test.

Don't Neglect Privacy

As shown by the backlash against surveillance programs, the general public doesn't like to have their images kept in digital archives for analysis. While getting users to participate in an eyetracking study can be difficult, you can make participation palatable by not storing facial images when possible.

Instead, just store the raw tracking recording and pair it with high level demographic data. Sometimes logging facial images might be necessary, such as for analyzing emotion. In these cases you should be transparent about the information is used and stored.

Continue reading %Eyetracking: How to Watch the Gap Between the Clicks (and Why)%

Using HealthKit with a Cordova App

Fr, 2015-08-14 15:00

HealthKit is a framework introduced in iOS 8 that provides a centralized, user coordinated and secure datastore for health and fitness related information. The HealthKit datastore is shared among apps so that they can access health and fitness related data.

In this tutorial I will show you how a Cordova app can read and update HealthKit data. I will create a simple app which will let users update height, weight and vitamin C consumption. To access the HealthKit framework I will use Telerik’s HealthKit Cordova Plugin.

Continue reading %Using HealthKit with a Cordova App%