Aug 13, 2014

Free & Easy HTML5 chat with Firebase, jQuery.& g+


Chatting has always been a very popular use for the internet, since the days of the the dial-up were mIRC was an extremely popular way to meet people , now you can see chats everywhere, they are very convenient on corporate (or even personal) web sites for dealing with customer service, sales, technical assistance, etc.

There are so many ways to create an HTML5 chat today, but I like this one for it's extremely flexible, easy to set up, works great and even though it's completely free, it can be scaled up later in complexity and user support to best suit your needs.

Firebase provides a Real-Time, Non-SQL cloud backend for our applications with very little effort but it can scale as your needs grows without any additional coding. the best part is that each Firebase DB gets a 50 connections Free quota and g+ can take care of the user's profile information.


So let's start by creating a new Firebase DataBase (or creating a new Firebase account), once you click "create" you will see the new DB in added to your list, the URL you see it's the one you will be using to work with the data stored in that DB.


To make log-in convenient for the user, we will be using the g+ sign-in button, so let's start by registering a new project in the Google Cloud Console.







After creating a new project, go to the active APIs list.



And turn ON the g+ API:







Now we need to create a new Client ID for Web Applications.


And we need to register the URL(s) of the site(s) we want to use this feature, if you don't register any site, anyone could easily steal you Client ID and use it in any page. Go to "Client ID for web application" and register your URL(s) in the "JAVASCRIPT ORIGINS" section. Don't forget to write down the "CLIENT ID".


In this example I used Free Google Drive HTML hosting, if you don't know how to use the service, here you can read an article, and here you can see a video describing how to do it. Custom URL is provided by gweb.io.

For the chat we need to create the following files:

  • index.html - Main file
  • gPlusLogin-async.js - Default asynchronous handler for g+ login.
  • gPlusLogin.js - Called by gPlusLogin-async.js to handle the API.
  • html5chat.js - This is were we store the logic for our chat.
And it's finally time to hit the code! Let's start with the good stuff, the html5chat.js:



Allow me to elaborate a little on what's going on:

messagesRef stores a Firebase reference pointing to our DB, simply write your's here.

Note: You can use the one provided in the example for testing.

$('#messageInput'.keypress here we use jQuery to monitor an HTML input with an id called messageInput, every time a key is pressed a function checks if it was the ENTER key (keyCode == 13)).

If the user pressed enter, we extract the user's name(#nameInput) and the message's text (#messageInput') and use the Firebase API method .push() to create a new object in the DB (with a random ID) with the information.

Now we need to listen the DB for changes to keep the messages windows updated, to do so we use the Firebase API method .on('child_added') to trigger a function and pass the new message (function (snapshot)) to a function, we use .limit() to limit the amount of values being watched to the last 40 so we don't need to keep watching the entire DB the whole time. which will eventually affect performance.

Finally we use the called function to parse and append the new value to the messages list.

Pro-Tip: You can have fun adding more advanced features like showing the current profile picture of the user who posted the message. Simply store the user's profile pic URL in Firebase.

Now it's time to take a look at gPlusLogin.js, which handles the data returned by the g+ API after the user logs in.



Here we have 2 functions: signinCallback and logIn,

signinCallback  is called after the user logs in and carries the APIs response, so here we check the result and make the necessary adjustments, if everything was fine with the response we call logIn which requests the user's information and makes all the adjustments to the website to show the user's data, make it available for other functions and makes final adjustments, like unlocking the chat text input field.

gPlusLogin-async.js it's simply the standard g+ asynchronous loader wrapped in a separate file.



And finally, we put all together inside index.html



Once we have all our files ready, the HTML it's quite simple, but you may notice that gPlusLogin-async.js it's after the   tab instead of within the  tag, this makes the login button to load asynchronously, this offer's best loading performance, also html5chat.js it's loaded at the end of the document, this also benefits loading performance.

Click on the image bellow to open a live demo:


Feel free to leave your comments or questions down below or in g+, also don't forget to share with us you're awesome chat implementation.

You can fork a copy of the Demo on Github:
https://github.com/reicek/firebase-gPlusHTML5chat/

Happy coding!

Apr 19, 2014

Introduction to HTML5 dynamic navigation and AngularJS



Everyday the number of devices with internet access it's increasing and with the arrival of new technologies, most businesses now has a website (at least) so the market of website development it's becoming more competitive and now proper UX it's becoming a standard instead of a plus.

The devices are becoming more powerful, most are even HD capable and HTML5 it's opening more possibilities everyday as web technologies evolve. HTML5 applications are becoming so powerful and flexible, that they are replacing the "good-old" native applications.

Google Docs it's a great example of  a modern web apps, it offers all you expect from a text editor for example, without the need to install it plus all the collaborative, web and cloud added capabilities. This technologies also benefit from the fact that they are always updated.

A very important aspect of modern web app is that when you browse from one section to the other, the whole page doesn't reload, but only a specific section changes. This not only makes the experience more convenient, it's also much faster.

Another reason that modern web apps are faster than old ones it's the addition of Async capabilities to HTML, allowing to display elements as they finish loading instead of always waiting for one to finish before starting the next one, along with smart programming the page becomes functional and visually correct long before it actually finishes loading.

AngularJS it's a great and convenient way to add both, Async loading and Dynamic navigation to a website or web app, and you don't need to be an AngularJS guru to start using it, and actually makes web development easier.

All the examples are hosted Free using Google Drive HTML hosting capabilities, if you haven't tried it already, it's probably the easiest way to publish and update your web sites and apps, plus it's completely free.

Let's hit the code!

First we need the "static" part, all you actually need is a title and a simple navigation menu like this:

Live Demo


It's remarkable the simplicity of the HTML5 markup. Now it's time to load the AngujarJS library and add the necessary HTML markup additions.

Let's take a look at the differences:



Awesome! It's curious how little code is required right? One of the ideas behind AngularJS and HTML5 is to keep things simple, modular and recyclable.

First I assigned "MyFirstDynamicNavigation" as the proyect's name, it is important to assign a name for your AngularJS project so that your code will be able to properly bind to the DOM.

Then I simply called the AngularJS libraries, conveniently stored on Google server's and in a minified version. I also load the Javascript file where we're going to store the Angular configuration.

For the links, all you need to do is to write "#/" plus any name you wish to assign to that section, this will be shown in the URL instead of the actual name of the file, this makes your site's nav bar clean and clear for the users.

Finally I declared the "article" tag as the container of my Templated HTML, you can use any tag you prefer.

Now we need to write the logic, let's see at the Javascript needed for this.



It is important to note that there are many ways to initualize your AngularJS app, I prefer this one for it's easy to scale and it keeps all it's data and functions safely inside a single scope, this avoids different Angular apps from getting mixed when running on the same browser at the same time. This also helps recycling the same pieces of code in different applications without the risk of errors when they run together.

The advantage of declaring your app this way becomes evident when you add the $routeProvider configuration. You can see how all the code it's contained in a single logical place, but it can be easily called to add more functions as needed.

$routeProvider keeps an eye on the last part of the browsers URL and uses it to choose which file (And controllers if you are using them) should be loaded. It depends on the "ngRoute" service The templateUrl should point to the file we want loaded for every particular location. It's common to assign the "/" address as the "welcome" screen. Note at the end a simple "otherwise" declaration tells the app to load a default template when the URL is unknown, we usually point back to the welcome screen or a special "Unknown URL" template.

Anything contained inside the pointed files will be loaded inside the ng-view tagged section while keeping the rest untouched, so it doesn't interrupt videos or animations.

For this example I created 4 HTML templates:

welcome.html
menu1.html
menu2.html
menu3.html

And that's it! You can see it working right here:

Live Demo

Don't forget to share your thoughts at the bottom of this article, also if you're coming to the Google I/O 2014, feel free to say hi, I'd love to meet you.

Happy coding!

Dec 11, 2013

Enable HTML5 Offline functionality to your gDrive hosted web apps!



Application Cache it's a pretty neat feature of HTML5, for it allows us to enable Offline functionality, faster loading times and reduced server load by caching a local copy of specific files when the user first access them, it can also be used to route the user to a special Offline version of our HTML code on specific parts of our site/app.

To do this one must create a special Manifest file, it is a very simple text file were we specify the offline cache behavior for our app, the most important parts are where we specify which documents should be cached and the creation date, this last one even though it's not technically required for the manifest to work, it is required to tell your App to update the cached version automatically next time a user logs, without it the cache will never be updated for the users and the only way they could get updates it's by cleaning they're browsers cache. It is also important to notice that most browsers won't allow more than 5Mb of cache for a single site.

We also must add a reference in our HTML code to tell the browser to look for the App Cache manifest, HTML5 makes this very easy, it's a very short declaration in the html tag of our app, for example:



Here we are telling the browser to look for a file called example.appcache in the root folder and use it as an appcache file.

I recommend reading a more detailed description of how to make an App Cache file on this w3schools.com article.

It sounds so easy right! but the trick is that the name it's not really relevant, the .appcache extension it's just done for standardization, technically it could be .awesomeOffline and still work (but please don't ;) standards makes collaborative work easier) what actually matters it's the MIMEtype of that file from the server which must be " text/cache-manifest " and that must be configured from the server, and most HTML hosting services doesn't have this option, and that includes the awesome Google Drive html hosting service, but as most things in this digital world, you can hack a way around this limitation.

To add the manifest file, first we need the ID of the root folder we are using for the gDrive HTML hosting for our application (in this article you can read more about how to host your HTML/JS/CSS code on gDrive), remember that you can find the ID for the folder when you open it from the web version of gDrive it's at the end of the URL in your browser.

Now that we have the folder ID, let's create a new script proyect and let's hit the code!

Let's get a good look at the code, it's very simple!



The most important part it's the MIMEtype, once created you can edit the text file to update it, personally I prefer to delete it and run the script again to create a new one, that way I'm sure that it's got the right date and everything.

AppCache opens a new world of possibilities for HTML5 web apps and web sites! Just be very careful when choosing which parts to cache, usually you should do thisonly with parts that doesn't change very often, like the libraries (and most of the Javascript code) and the CSS. If used properly it will greatly enhance the speed and therefore the user experience, and that must always be our main priority, remember that we are now entering a coding age where UX design really makes the difference.

Feel free to post your request, questions, ideas or simply say hi! on g+ or at the end of this article, your feedback it's very important and greatly appreciated.

Happy coding!