Creating a File Encryption App with JavaScript

javascript-file-encryption

Security and privacy are hot topics at the moment. This is an opportunity for us to take an introspective look into the way we approach security. It is all a matter of compromise – convenience versus total lock down. Today’s tutorial is an attempt to mix a bit of both.

The app we are going to build today is an experiment that will allow people to choose files from their computers and encrypt them client-side with a pass phrase. No server-side code will be necessary, and no information will be transferred between client and server. To make this possible we will use the HTML5 FileReader API, and a JavaScript encryption library - CryptoJS.

Note that the app doesn’t encrypt the actual file, but a copy of it, so you won’t lose the original. But before we start, here are a few issues and limitations:

Issues and limitations

The 1MB limit

If you play with the demo, you will notice that it doesn’t allow you to encrypt files larger than 1mb. I placed the limit, because the HTML5 download attribute, which I use to offer the encrypted file for download, doesn’t play well with large amounts of data. Otherwise it would cause the tab to crash in Chrome, and the entire browser to crash when using Firefox. The way around this would be to use the File System API and to write the actual binary data there, but it is supported only in Chrome for now. This is not an issue with the encryption speed (which is quite fast), but with offering the file for download.

What about HTTPS?

When it comes to encrypting data and securing information, people naturally expect the page to be loaded through HTTPS. In this case I believe it is not necessary, as apart from the initial download of the HTML and assets, no data is transferred between you and the server – everything is done client-side with JavaScript.  If this bothers you, you can just download the demo and open it directly from your computer.

How secure is it?

The library that I use - CryptoJS - is open source, so I believe it to be trustworthy. I use the AES algorithm from the collection, which is known to be secure. For best results, use a long pass phrase that is difficult to guess.

JavaScript File Encryption App

JavaScript File Encryption App

The HTML

The markup of the app consists of a regular HTML5 document and a few divs that separate the app into several individual screens. You will see how these interact in the JavaScript and CSS sections of the tutorial.

index.html

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8"/>
		<title>JavaScript File Encryption App</title>
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<link href="http://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet" />
		<link href="assets/css/style.css" rel="stylesheet" />
	</head>

	<body>

		<a class="back"></a>

		<div id="stage">

			<div id="step1">
				<div class="content">
					<h1>What do you want to do?</h1>
					<a class="button encrypt green">Encrypt a file</a>
					<a class="button decrypt magenta">Decrypt a file</a>
				</div>
			</div>

			<div id="step2">

				<div class="content if-encrypt">
					<h1>Choose which file to encrypt</h1>
					<h2>An encrypted copy of the file will be generated. No data is sent to our server.</h2>
					<a class="button browse blue">Browse</a>

					<input type="file" id="encrypt-input" />
				</div>

				<div class="content if-decrypt">
					<h1>Choose which file to decrypt</h1>
					<h2>Only files encrypted by this tool are accepted.</h2>
					<a class="button browse blue">Browse</a>

					<input type="file" id="decrypt-input" />
				</div>

			</div>

			<div id="step3">

				<div class="content if-encrypt">
					<h1>Enter a pass phrase</h1>
					<h2>This phrase will be used as an encryption key. Write it down or remember it; you won't be able to restore the file without it. </h2>

					<input type="password" />
					<a class="button process red">Encrypt!</a>
				</div>

				<div class="content if-decrypt">
					<h1>Enter the pass phrase</h1>
					<h2>Enter the pass phrase that was used to encrypt this file. It is not possible to decrypt it without it.</h2>

					<input type="password" />
					<a class="button process red">Decrypt!</a>
				</div>

			</div>

			<div id="step4">

				<div class="content">
					<h1>Your file is ready!</h1>
					<a class="button download green">Download</a>
				</div>

			</div>
		</div>

	</body>

	<script src="assets/js/aes.js"></script>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="assets/js/script.js"></script>

</html>

Only one of the step divs is visible at a time. Depending on the choice of the user – to encrypt or decrypt – a class name is set on the body element. With CSS, this class name hides the elements with either the if-encrypt or if-decrypt classes. This simple gating allows us to write cleaner JavaScript that is minimally involved with the UI.

Choose File To Encrypt

Choose File To Encrypt

The JavaScript Code

As I mentioned in the intro, we are going to use the HTML5 FileReader API (support) and the CryptoJS library together. The FileReader object lets us read the contents of local files using JavaScript, but only of files that have been selected explicitly by the user through the file input’s browse dialog. You can see how this is done in the code below. Notice that most of the code handles the transitions between the different screens of the app, and the actual reading of the file happens from line 85.

assets/js/script.js

$(function(){

	var body = $('body'),
		stage = $('#stage'),
		back = $('a.back');

	/* Step 1 */

	$('#step1 .encrypt').click(function(){
		body.attr('class', 'encrypt');

		// Go to step 2
		step(2);
	});

	$('#step1 .decrypt').click(function(){
		body.attr('class', 'decrypt');
		step(2);
	});

	/* Step 2 */

	$('#step2 .button').click(function(){
		// Trigger the file browser dialog
		$(this).parent().find('input').click();
	});

	// Set up events for the file inputs

	var file = null;

	$('#step2').on('change', '#encrypt-input', function(e){

		// Has a file been selected?

		if(e.target.files.length!=1){
			alert('Please select a file to encrypt!');
			return false;
		}

		file = e.target.files[0];

		if(file.size > 1024*1024){
			alert('Please choose files smaller than 1mb, otherwise you may crash your browser. \nThis is a known issue. See the tutorial.');
			return;
		}

		step(3);
	});

	$('#step2').on('change', '#decrypt-input', function(e){

		if(e.target.files.length!=1){
			alert('Please select a file to decrypt!');
			return false;
		}

		file = e.target.files[0];
		step(3);
	});

	/* Step 3 */

	$('a.button.process').click(function(){

		var input = $(this).parent().find('input[type=password]'),
			a = $('#step4 a.download'),
			password = input.val();

		input.val('');

		if(password.length<5){
			alert('Please choose a longer password!');
			return;
		}

		// The HTML5 FileReader object will allow us to read the 
		// contents of the	selected file.

		var reader = new FileReader();

		if(body.hasClass('encrypt')){

			// Encrypt the file!

			reader.onload = function(e){

				// Use the CryptoJS library and the AES cypher to encrypt the 
				// contents of the file, held in e.target.result, with the password

				var encrypted = CryptoJS.AES.encrypt(e.target.result, password);

				// The download attribute will cause the contents of the href
				// attribute to be downloaded when clicked. The download attribute
				// also holds the name of the file that is offered for download.

				a.attr('href', 'data:application/octet-stream,' + encrypted);
				a.attr('download', file.name + '.encrypted');

				step(4);
			};

			// This will encode the contents of the file into a data-uri.
			// It will trigger the onload handler above, with the result

			reader.readAsDataURL(file);
		}
		else {

			// Decrypt it!

			reader.onload = function(e){

				var decrypted = CryptoJS.AES.decrypt(e.target.result, password)
										.toString(CryptoJS.enc.Latin1);

				if(!/^data:/.test(decrypted)){
					alert("Invalid pass phrase or file! Please try again.");
					return false;
				}

				a.attr('href', decrypted);
				a.attr('download', file.name.replace('.encrypted',''));

				step(4);
			};

			reader.readAsText(file);
		}
	});

	/* The back button */

	back.click(function(){

		// Reinitialize the hidden file inputs,
		// so that they don't hold the selection 
		// from last time

		$('#step2 input[type=file]').replaceWith(function(){
			return $(this).clone();
		});

		step(1);
	});

	// Helper function that moves the viewport to the correct step div

	function step(i){

		if(i == 1){
			back.fadeOut();
		}
		else{
			back.fadeIn();
		}

		// Move the #stage div. Changing the top property will trigger
		// a css transition on the element. i-1 because we want the
		// steps to start from 1:

		stage.css('top',(-(i-1)*100)+'%');
	}

});

I obtain the contents of the files as a data uri string (support). Browsers allow you to use these URIs everywhere a regular URL would go. The benefit is that they let you store the content of the resource directly in the URI, so we can, for example, place the contents of the file as the href of a link, and add the download attribute (read more) to it, to force it to download as a file when clicked.

I use the AES algorithm to encrypt the data uri with the chosen password, and to offer it as a download. The reverse happens when decrypting it. No data ever reaches the server. You don’t even need a server for that matter, you can open the HTML directly from a folder on your computer, and use it as is.

Enter a Pass Phrase

Enter a Pass Phrase

The CSS

I will present only the more interesting parts of the CSS here, you can see the rest in the stylesheet from the downloadable zip. The first thing to present, are the styles that create the layout and its ability to scroll smoothly between screens by changing the top property of the #stage element.

assets/css/styles.css

body{
	font:15px/1.3 'Raleway', sans-serif;
	color: #fff;
	width:100%;
	height:100%;
	position:absolute;
	overflow:hidden;
}

#stage{
	width:100%;
	height:100%;
	position:absolute;
	top:0;
	left:0;

	transition:top 0.4s;
}

#stage > div{  /* The step divs */
	height:100%;
	position:relative;
}

#stage h1{
	font-weight:normal;
	font-size:48px;
	text-align:center;
	color:#fff;
	margin-bottom:60px;
}

#stage h2{
	font-weight: normal;
	font-size: 14px;
	font-family: Arial, Helvetica, sans-serif;
	margin: -40px 0 45px;
	font-style: italic;
}

.content{
	position:absolute;
	text-align:center;
	left:0;
	top:50%;
	width:100%;
}

Because the step divs are set to a 100% width and height, they automatically take the full dimensions of the browser window without having to be resized.

Another interesting piece of code, are the conditional classes that greatly simplify our JavaScript:

[class*="if-"]{
	display:none;
}

body.encrypt .if-encrypt{
	display:block;
}

body.decrypt .if-decrypt{
	display:block;
}

This way, the encrypt and decrypt classes of the body control the visibility of the elements that have the respective if-* class.

We’re done!

With this our JavaScript encryption app is ready! You can use it to share pictures and documents with friends by sending them the version encrypted with a pre-agreed pass phrase. Or you can put the HTML of the app on a flash drive, along with your encrypted files, and open the index.html directly to decrypt them.

12 Awesome CSS3 Features That You Can Finally Start Using

12-awesome-css-features

If you are like me, when you see an impressive demo of a new CSS3 feature, you can’t wait to start using it in websites. Of course, then you see that it is available in only one or two of the major browsers (and this never includes IE), so ultimately you decide to wait. I have good news for you – with the latest browser releases, there are a few awesome features that are finally supported everywhere, and you can start using them right now!

A word of caution – most of these features will not work in older versions of IE (9 and below). If these browsers are a large portion of your demographic, I am afraid that you will have to rely on fallbacks. But for the rest of us, here is what modern browsers have to offer:

1. CSS Animations and Transitions

CSS animations are finally available in all major browsers, even in IE (since version 10). There are two ways to create CSS animations. The first is very easy, it is done through animating the changes of CSS properties with the transition declaration. With transitions, you can create hover or mouse down effects, or you can trigger the animation by changing the style of an element with JavaScript. You can see the transition below by hovering over the planet – this will cause the rocket to close in.

The second way for defining animations is a bit more complicated – it involves the description of specific moments of the animation with the @keyframe rule. This allows you to have repeating animations that don’t depend on user actions or JavaScript to get triggered. Hit the Edit button to see the code.

(Play with our code editor on Tutorialzine.com)

There is much to learn about CSS animations, and I suggest that you start from this Mozilla Developer Network (MDN) article. If you are curious about browser support, see this compatibility table.

2. Calculating Values With calc()

Another new and awesome CSS feature is the calc() function. It allows you to do simple arithmetic calculations in CSS. You can use it anywhere a length or a size is required. What is even cooler, is that you can freely mix different units, like percentages and pixels. This makes a lot of layout hacks that you might have used in the past obsolete. The best news? It works in IE9 and up, prefix-free.

(Play with our code editor on Tutorialzine.com)

Learn more about the calc() function here, or see a compatibility table.

3. Advanced Selectors

These days, if you assign IDs to elements only so you can style them, you are probably doing it wrong. CSS 2.1 and CSS 3 introduced a number of powerful selectors that can make your layouts cleaner, and your stylesheets more awesome.

These are supported in all major browsers including IE9 and up. Hit Edit to see the source code for the example.

(Play with our code editor on Tutorialzine.com)

Learn more about these selectors here, or take a look at which browsers support them.

4. Generated Content and Counters

Generated content is a powerful tool in the hands of developers, made available by the ::before and ::after pseudo elements. This feature lets you use less HTML to achieve the same layouts. This is especially beneficial in cases where you need extra box shadows or other visual elements that would require extra spans or divs. In the end, you get a more minimal and semantically correct HTML.

CSS3 also gives pseudo elements access to counters, which can be incremented with a CSS rule. They can also access attributes from the parent elements that contain them. See the source of the example below.

(Play with our code editor on Tutorialzine.com)

Generated content is supported everywhere, including IE9 and up.

5. Gradients

Gradients give web designers the power to create smooth transitions between colors without having to resort to images. CSS gradients also look great on retina displays, because they are generated on the fly. They can be linear or radial, and can be set to repeat. They have been around for some time, but after a few minor syntax changes over the last months, they are finally available nearly everywhere, prefix-free!

(Play with our code editor on Tutorialzine.com)

See a detailed tutorial here, and a compatibility table here.

6. Webfonts

Can you imagine that there was a time when we were limited to only a handful of “web-safe” fonts and nothing else? It is hard to believe, given that today we have services like Google Fonts and typekit, which let you embed beautiful fonts by simply including a stylesheet in your page. There are even icon fonts like fontawesome, which contain pretty vector icons, instead of letters or numbers. This was all made possible by the @font-face rule, which lets you define the name, characteristics and source files for fonts, which you can later refer in your font/font-family declarations.

(Play with our code editor on Tutorialzine.com)

Note that due to security limitations in browsers, I was not able to embed a local font in the inline editor above, so I used one from Google Webfonts instead. But you can see a working example here.

With some workarounds, webfonts work on browsers as old as IE6. The two hosted services I mentioned above handle these cases for you, so you don’t have to.

7. Box Sizing

The single biggest cause for headaches for CSS beginners is the box model. The standardization bodies have probably had their reasons, but it doesn’t feel at all intuitive to have the CSS width and height of an element affected by its padding and borders. This little (mis)feature breaks layouts and wreaks havoc, but finally there is a way to restore our sanity by using the box-sizing rule. You can set it to border-box, which makes elements behave exactly the way you expect. See for yourself:

(Play with our code editor on Tutorialzine.com)

Learn more about the box-sizing rule here, or see the compatibility table.

8. Border Images

The border-image property allows you to display custom designed borders around elements. The borders are contained in a single image (sprite), with each region of that image corresponding to a different part of the border. Here is the image used in the below example.

(Play with our code editor on Tutorialzine.com)

For a more in-depth look, check out this MDN page and this article on CSS tricks. Border images are supported in all major browsers and IE11.

9. Media Queries

Media queries are an absolute must if you are serious about web design. They have been around for a while, but are worth a mention, because they have transformed the way we build websites. It used to be that you had a regular website, wide enough to fit the smallest monitor resolution used at the time, and a separate mobile website. These days, we build sites that are responsive and which adapt to the type of device, orientation and resolution.

Media queries are surprisingly easy to use – all you need to do is to enclose CSS styles in a block guarded by a @media rule. Each @media block is activated when one or more conditions are met. As an example, try resizing this page. I have also included it in the editor below; try removing the the @media block to see what happens.

(Play with our code editor on Tutorialzine.com)

The media query can contain checks for the device resolution and orientation, color depth, pixel density and more. Read an in-depth article here, and see the compatibility table.

10. Multiple Backgrounds

With multiple backgrounds, designers can achieve very interesting effects. They can stack different images as backgrounds of the same element. Each image (or layer) can be moved and animated independently, like you can see in the demo below (try hovering over the image with your mouse). All background-releated CSS rules can now take a comma-delimited list of properties, each for the specific background image:

(Play with our code editor on Tutorialzine.com)

For more information on multiple backgrounds, see here. Browser support is very good – all recent versions support the rule (see the table).

11. CSS Columns

Column-based layouts were notoriously difficult to pull off in CSS. It usually involved using JavaScript or server-side processing that splits the content into different elements. This is unnecessarily complicated and takes precious development time away from what really matters. Fortunately, now there is a way around this by using the CSS columns rule:

(Play with our code editor on Tutorialzine.com)

There is good support for this rule, although it still requires prefixes. Where things break down is with the support of some of the other column-related rules and differences between browsers in handling corner cases.

12. CSS 3D Transforms

There is nothing more flashy and full with eye-candy than an impressive 3D CSS demo. Although its utility outside of demos or portfolio sites is questionable, 3D CSS offers some powerful features to designers and developers that can win the hearts of users if done with good measure.

Browse through the source code of the following example by hitting the Edit button, to see how it was made.

(Play with our code editor on Tutorialzine.com)

This code was modeled after our Apple-like Login Form tutorial, which I advise you to read. If you want to learn more about 3D CSS, take a look at this detailed introduction. If you don’t need to target old IE, browser support is also very good.

Other Worthy Mentions

There are other notable features that are worth mentioning. If you haven’t already, you should stop using prefixes for border-radius and box-shadow. You can also now use data-uri as background images in every browser. opacity is also supported everywhere, as well as the very useful background-size property.

There is still some time before cross-browser support lands for flexbox, @supports, filters, and CSS masks, but I am sure it will be worth the wait!

Buttons With Built-in Progress Meters

buttons-progress-meters

Progress bars have become quite popular lately, and there are lots of plugins that can help you add one to your site. But how do you make one yourself? The problem is that there are plenty of implementations already, so in this tutorial, we are going to code something different – buttons that have built in progress meters.

They will be perfect for displaying progress while submitting forms or loading content via AJAX. They will also use CSS3 styles and transitions to make them easy to customize.

The HTML

In the first section of the tutorial, we will write the HTML markup. It comes in the form of a standard HTML5 document which includes two additional resources that we will discuss later – the styles.css stylesheet and the script.js JavaScript file. Additionally, I have included the jQuery library, and the Raleway font from Google web fonts.

index.html

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8"/>
		<title>Tutorial: Buttons with built-in progress meters</title>

		<link href="http://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet" />

		<!-- The Stylesheets -->
		<link href="assets/css/style.css" rel="stylesheet" />

	</head>

	<body>

		<h1>Progress Buttons</h1>

		<a id="submitButton" href="#" class="progress-button">Submit</a>

		<a id="actionButton" href="#" class="progress-button green" data-loading="Working.." data-finished="Finished!" data-type="background-bar">Action!</a>

		<a id="generateButton" href="#" class="progress-button red" data-loading="Generating.." data-finished="Download" data-type="background-vertical">Generate</a>

		<h1>Progress Control</h1>

		<a id="controlButton" href="#" class="progress-button">Start</a>

		<div class="control-area">
			<a class="command increment">Increment</a>
			<a class="command set-to-1">Set to 1%</a>
			<a class="command set-to-50">Set to 50%</a>
			<a class="command finish">Finish</a>
		</div>

		<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
		<script src="assets/js/script.js"></script>

	</body>
</html>

The markup is pretty simple. The progress buttons are defined as regular hyperlinks. In order to be recognized by the plugin and turned into buttons with built-in progress bars, they need to have the .progress-button class. Buttons can also be configured by setting three data-* attributes:

  • data-type specifies what type of progress bars will be shown. Currently three types are supported: background-horizontal (the default), background-bar and background-vertical.
  • data-loading specifies the text that is shown while the progress bar is moving. The default value is Loading..
  • data-finished holds the text that is set on the button when the progress is done. The default value is Done!

If you omit an attribute, the default value will be used.

Buttons With Built-in Progress Meters

Buttons With Built-in Progress Meters

The jQuery Code

In this part of the tutorial, we are going to write the JavaScript and jQuery code to make the buttons work. The code is organized as 6 jQuery plugins that share a common name – progressInitialize, progressStart, progressIncrement, progressTimed, progressSet and progressFinish. I have provided plenty of comments in the code, so you can dig right in:

assets/js/script.js

$(document).ready(function(){

	// Convert all the links with the progress-button class to
	// actual buttons with progress meters.
	// You need to call this function once the page is loaded.
	// If you add buttons later, you will need to call the function only for them.

	$('.progress-button').progressInitialize();

	// Listen for clicks on the first three buttons, and start 
	// the progress animations

	$('#submitButton').click(function(e){
		e.preventDefault();

		// This function will show a progress meter for
		// the specified amount of time

		$(this).progressTimed(2);
	});

	$('#actionButton').click(function(e){
		e.preventDefault();
		$(this).progressTimed(2);
	});

	$('#generateButton').one('click', function(e){
		e.preventDefault();

		// It can take a callback

		var button = $(this);
		button.progressTimed(3, function(){

			// In this callback, you can set the href attribute of the button
			// to the URL of the generated file. For the demo, we will only 
			// set up a new event listener that alerts a message.

			button.click(function(){
				alert('Showing how a callback works!');
			});
		});
	});

	// Custom progress handling

	var controlButton = $('#controlButton');

	controlButton.click(function(e){
		e.preventDefault();

		// You can optionally call the progressStart function.
		// It will simulate activity every 2 seconds if the
		// progress meter has not been incremented.

		controlButton.progressStart();
	});

	$('.command.increment').click(function(){

		// Increment the progress bar with 10%. Pass a number
		// as an argument to increment with a different amount.

		controlButton.progressIncrement();
	});

	$('.command.set-to-1').click(function(){

		// Set the progress meter to the specified percentage

		controlButton.progressSet(1);
	});

	$('.command.set-to-50').click(function(){
		controlButton.progressSet(50);
	});

	$('.command.finish').click(function(){

		// Set the progress meter to 100% and show the done text.
		controlButton.progressFinish();
	});

});

// The progress meter functionality is available as a series of plugins.
// You can put this code in a separate file if you wish to keep things tidy.

(function($){

	// Creating a number of jQuery plugins that you can use to
	// initialize and control the progress meters.

	$.fn.progressInitialize = function(){

		// This function creates the necessary markup for the progress meter
		// and sets up a few event listeners.

		// Loop through all the buttons:

		return this.each(function(){

			var button = $(this),
				progress = 0;

			// Extract the data attributes into the options object.
			// If they are missing, they will receive default values.

			var options = $.extend({
				type:'background-horizontal',
				loading: 'Loading..',
				finished: 'Done!'
			}, button.data());

			// Add the data attributes if they are missing from the element.
			// They are used by our CSS code to show the messages
			button.attr({'data-loading': options.loading, 'data-finished': options.finished});

			// Add the needed markup for the progress bar to the button
			var bar = $('<span class="tz-bar ' + options.type + '">').appendTo(button);

			// The progress event tells the button to update the progress bar
			button.on('progress', function(e, val, absolute, finish){

				if(!button.hasClass('in-progress')){

					// This is the first progress event for the button (or the
					// first after it has finished in a previous run). Re-initialize
					// the progress and remove some classes that may be left.

					bar.show();
					progress = 0;
					button.removeClass('finished').addClass('in-progress')
				}

				// val, absolute and finish are event data passed by the progressIncrement
				// and progressSet methods that you can see near the end of this file.

				if(absolute){
					progress = val;
				}
				else{
					progress += val;
				}

				if(progress >= 100){
					progress = 100;
				}

				if(finish){

					button.removeClass('in-progress').addClass('finished');

					bar.delay(500).fadeOut(function(){

						// Trigger the custom progress-finish event
						button.trigger('progress-finish');
						setProgress(0);
					});

				}

				setProgress(progress);
			});

			function setProgress(percentage){
				bar.filter('.background-horizontal,.background-bar').width(percentage+'%');
				bar.filter('.background-vertical').height(percentage+'%');
			}

		});

	};

	// progressStart simulates activity on the progress meter. Call it first,
	// if the progress is going to take a long time to finish.

	$.fn.progressStart = function(){

		var button = this.first(),
			last_progress = new Date().getTime();

		if(button.hasClass('in-progress')){
			// Don't start it a second time!
			return this;
		}

		button.on('progress', function(){
			last_progress = new Date().getTime();
		});

		// Every half a second check whether the progress 
		// has been incremented in the last two seconds

		var interval = window.setInterval(function(){

			if( new Date().getTime() > 2000+last_progress){

				// There has been no activity for two seconds. Increment the progress
				// bar a little bit to show that something is happening

				button.progressIncrement(5);
			}

		}, 500);

		button.on('progress-finish',function(){
			window.clearInterval(interval);
		});

		return button.progressIncrement(10);
	};

	$.fn.progressFinish = function(){
		return this.first().progressSet(100);
	};

	$.fn.progressIncrement = function(val){

		val = val || 10;

		var button = this.first();

		button.trigger('progress',[val])

		return this;
	};

	$.fn.progressSet = function(val){
		val = val || 10;

		var finish = false;
		if(val >= 100){
			finish = true;
		}

		return this.first().trigger('progress',[val, true, finish]);
	};

	// This function creates a progress meter that 
	// finishes in a specified amount of time.

	$.fn.progressTimed = function(seconds, cb){

		var button = this.first(),
			bar = button.find('.tz-bar');

		if(button.is('.in-progress')){
			return this;
		}

		// Set a transition declaration for the duration of the meter.
		// CSS will do the job of animating the progress bar for us.

		bar.css('transition', seconds+'s linear');
		button.progressSet(99);

		window.setTimeout(function(){
			bar.css('transition','');
			button.progressFinish();

			if($.isFunction(cb)){
				cb();
			}

		}, seconds*1000);
	};

})(jQuery);

progressInitialize sets up an event listener for the progress custom event that the other functions call whenever the meter needs to be updated. Thanks to the custom event, we can have entirely independent functions like progressStart, which manages its own timer and state – progresInitialize need not know about progressStart.

The other important thing is that we are setting two special classes on the buttons – .in-progress while the progress meter is moving, and .finished when it’s ready. They are used to update the text of the buttons as you will see in the next section.

The CSS

I mentioned that we are setting two CSS classes on the buttons – .in-progress and .finished. But how does adding one of these classes change the text of the button? Simple – we are using a CSS trick that involves the CSS3 attr operator, which when combined with content, can set the text of a :before or :after pseudo element to that of the attribute of the element. It will become clearer once you see it for yourself (lines 44-52):

assets/css/styles.css

.progress-button{
	display: inline-block;
	font-size:24px;
	color:#fff !important;
	text-decoration: none !important;
	padding:14px 60px;
	line-height:1;
	overflow: hidden;
	position:relative;

	box-shadow:0 1px 1px #ccc;
	border-radius:2px;

	background-color: #51b7e6;
	background-image:-webkit-linear-gradient(top, #51b7e6, #4dafdd);
	background-image:-moz-linear-gradient(top, #51b7e6, #4dafdd);
	background-image:linear-gradient(top, #51b7e6, #4dafdd);
}

/* Hide the original text of the button. Then the loading or finished
   text will be shown in the :after element above it. */

.progress-button.in-progress,
.progress-button.finished{
	color:transparent !important;
}

.progress-button.in-progress:after,
.progress-button.finished:after{
	position: absolute;
	z-index: 2;
	width: 100%;
	height: 100%;
	text-align: center;
	top: 0;
	padding-top: inherit;
	color: #fff !important;
	left: 0;
}

/* If the .in-progress class is set on the button, show the
   contents of the data-loading attribute on the butotn */

.progress-button.in-progress:after{
	content:attr(data-loading);
}

/* The same goes for the .finished class */

.progress-button.finished:after{
	content:attr(data-finished);
}

/* The colorful bar that grows depending on the progress */

.progress-button .tz-bar{
	background-color:#e667c0;
	height:3px;
	bottom:0;
	left:0;
	width:0;
	position:absolute;
	z-index:1;

	border-radius:0 0 2px 2px;

	-webkit-transition: width 0.5s, height 0.5s;
	-moz-transition: width 0.5s, height 0.5s;
	transition: width 0.5s, height 0.5s;
}

/* The bar can be either horizontal, or vertical */

.progress-button .tz-bar.background-horizontal{
	height:100%;
	border-radius:2px;
}

.progress-button .tz-bar.background-vertical{
	height:0;
	top:0;
	width:100%;
	border-radius:2px;
}

The rest of the code styles the buttons and the built-in progress meter. In styles.css I have also included two additional color themes and some other rules that are not given here, but which you can see by browsing the source yourself.

We’re Done!

The code we wrote today is ready for customizations. Simply open styles.css in your favorite code editor and change the colors, fonts or styles so they match your site. Change the text by editing the HTML and the data attributes. Or you can even improve the code with some cool new feature. In this case be sure to share it in the comment section :)

20 Impressive Examples for Learning WebGL with Three.js

20-impressive-threejs-examples

By now you have probably heard about Three.js – a library which makes working with 3D in the browser easy. With it, you can create the building blocks of 3D modeling – cameras, meshes, lights and more, and apply animations on them. Three.js can draw a scene using a Canvas element,  SVG, CSS3D or WebGL.

In this article, you will find a collection of demos, tutorials and resources that will inspire you to learn more about the library.

Experiments and Demos

The impressive demos that you see below are made with the Three.js library and WebGL as a renderer. It is possible to use WebGL directly, but choosing Three.js makes development easier and results in only a fraction of the code. Here are some of the things that are possible with the library:

1. Nucleal

Nucleal is a WebGL experiment, powered by the Three.js. It breaks photos down into thousands of particles that are transformed by physics. You can choose any combination of photo, speed and effects. The animations run smoothly which is even more impressive.

Nucleal

Nucleal

2. Lights

Lights is an amazing visual experience, powered by Three.js, which syncrhonizes colors and shapes to music. You fly through a scene filled with colorful shapes, which you can interact with by clicking. Headphones are recommended.

Lights

Lights

3. Just A Reflektor

“Just A Reflektor” is an interactive film that lets you cast a virtual projection on your computer screen by holding up your mobile device in front of your computer’s webcam. That way, you control all of the visual effects in the experience by moving your phone or tablet through the physical space around you. See some of the amazing effects on the tech page, and the behind the scenes video.

Just A Reflektor

Just A Reflektor

4. Arms Globe

Arms Globe is a visualization experiment which overlays the world trade of small arms and ammunition on top of a model of the earth which you can rotate in 3D space. You can filter the data set by years and types of ammunition. The visualization is very impressive and runs smoothly.

Arms Globe

Arms Globe

5. Google Street View Hyperlapse

This experiment downloads Google Streetview data between two destinations, and turns it into an animation of the trip. You can pause and take a look around, or you can drag a target on the map on the top-right which the camera will follow. Give it a few minutes to load or watch this video to see it in action.

Google Street View Hyperlapse

Google Street View Hyperlapse

6. Find Your Way To Oz

This is a promotional website for the Oz the Great and Powerful movie. It combines beautiful artwork with HTML5 and WebGL into immersive experience. It takes place in the circus from the beginning of the movie. You can interact with the environment and use your web cam.

Find Your Way To Oz

Find Your Way To Oz

7. Google Zeitgeist

Google’s Zeitgeist for 2012 included a WebGL powered world map which presented the search trends and important events from the past year. Click the “Watch the year in review” button to see it.

Google Zeitgeist

Google Zeitgeist

8. Ironbane

Ironbane is a massively multiplayer online game powered by WebGL and Three.js. You can collect items, interact with other players and explore the open world. The game follows a retro style inspired by Minecraft and runs smoothly. The game is open source and both the client and server side are written in JavaScript. You can play without opening an account, so you can quickly try it for yourself.

Ironbane

Ironbane

9. Cube Slam

Cube Slam is my favorite Three.js powered game from this list. It is a spin of the classic pong game, but moves it into 3D space. You can play against your friends or computer-controlled bear. The game uses WebRTC so you see a video of your friend’s webcam. For a behind the scenes, read through this blog post by one of the creators.

Cube Slam

Cube Slam

10. HexGL

HexGL is a futuristic, fast-paced racing game built using HTML5, JavaScript and WebGL, with the help of Three.js. It is a tribute to the original Wipeout and F-Zero series. It is a graphically heavy game, approaching the level of desktop games from a few years ago. Luckily, you can lower the level of detail before playing. Here is a video from the game author explaining how he made the game.

HexGL

HexGL

11. Chrome World Wide Maze

This is a Chrome Experiment by Google that lets you turn any web page into a 3 dimensional maze through which you move a ball. What is even cooler, is that the ball is controlled from your smartphone.

Chrome World Wide Maze

Chrome World Wide Maze

12. HelloRun

HelloRun is a WebGL game powered by Three.js that puts you in the hull of a spaceship and forces you to find your way by jumping through hurdles. The game has great visuals and progressively speeds up and becomes more difficult.

HelloRun

HelloRun

13. Hello Racer

Hello Racer is an impressive visualization of a Formula 1 racing car, powered by WebGL and Three.js. It features life-like reflections and shadows. You can even drive it around with the WASD keys.

Hello Racer

Hello Racer

14. 360 Car Visualizer

This is another experiment that features detailed car visualizations. This time you can choose the car model and color. The colors are applied dynamically and all the textures are updated to match.

360 Car Visualizer

360 Car Visualizer

15. Google Maps Cube

Google Maps Cube is a game that presents you with a 3D maps cube. Your job is to navigate a ball through the city and reach checkpoints.

Google Maps Cube

Google Maps Cube

16. CSS3D Periodic Table

This is an impressive demo of Three.js. Instead of WebGL, this experiment uses CSS3D to render the chemical elements boxes. You can choose between four layouts: table, sphere, helix and grid.

CSS3D Periodic Table

CSS3D Periodic Table

17. WebGL Globe

The WebGL Globe is a visualization experiment that, similar to the arms globe, presents data overlayed on a globe floating in 3d space. This example is centered around population by city, but you can see versions with different data sets here.

WebGL Globe

WebGL Globe

18. Obsidian

Obsidian is a WebGL demo that synchronizes floating shapes and colors to music. Although there is a slider at the bottom, this is not a video – the effects are generated in real time.

Obsidian

Obsidian

19. Indra’s Net

This demo presents a multidimensional web of raindrops that reflect each other and the world around them. Even though a very large number of objects is involved, the rendering is still quite fast.

Indra's Net

Indra’s Net

20. Planet Maker

Planet Maker is a web app powered by WebGL and Three.js that lets you create real or imaginary planets. You can choose from several surface texture options, tweak the lighting and atmosphere, add or remove clouds, upload your own imagery, or wrap a ring around them.

Planet Maker

Planet Maker

Bonus: WebGL Nyan Cat

Frankly, no collection of WebGL resources is complete without a nyan cat. Enjoy!

WebGL Nyan Cat

WebGL Nyan Cat

Find even more impressive WebGL demos here:

Tutorials and Examples

Now that you are sold on Three.js, where do you start? Here is a collection of tutorials, examples, presentations and videos to get you started.

Getting Started

  • Introduction to WebGL - this is a presentation with live code examples that will introduce you to WebGL and Three.js.
  • Getting Started With Three.js – a great tutorial that explains the basics of 3D modeling using the library. It is easy to read and beginner friendly.
  • Getting Started – this is the official getting started tutorial. It explains the basics for getting Three.js running.
  • Creating Particles With Three.js – another tutorial by Paul Lewis, in which he explains how to develop a cool particle system (demo).
  • WebGL Academy – if you wish to learn pure WebGL, without Three.js, you can follow this step by step guide. Here you write code in an editor and see a real-time preview of the result.

Examples

  • Basic Three.js Examples - These are beginner-friendly examples, that are easy to follow and well-documented. Start with this page once you’ve completed the getting started posts.
  • Three.js examples by Stemkoski – This page might look like it came out of the late 90s, but it actually quite relevant. It hosts a large collection of Three.js examples with thoroughly commented source code, which cover a broad range of topics.
  • Official Three.js Examples – These examples demonstrate every part of the library. Unfortunately the source code is lacking on comments and might be difficult to follow at times.

Videos

More Resources

  • The official Three.js reference - you should bookmark this and have it opened in a tab at all times.
  • The official wiki – contains a FAQ section and links to various articles and other resources that you might find useful.
  • Learning Three.js – this is a blog dedicated to publishing Three.js tutorials. Each post explains how to make one of the popular demos that you see throughout the web.
  • Three.js Editor – this is a code editor for three.js with live preview. You can use it to quickly try out things with the library. You can share your experiments with others and save your progress.
  • Alternative documentation – this is an autogenerated index of all the methods in the library.
  • Google+ page - here you can find fresh news and links about the library.
  • SO questions, tagged with three.js. Reading through the most popular questions and answers now will save you time and headaches later on.
  • WebGL Subreddit – this is not focused only on three.js, but is worth browsing nonetheless.

Do you know of other resources that should be included here? Share them in the comment section.

Quick Tip: Add a Progress Bar to Your Site

quick-tip-progress-bar

Since the advent of mobile, web sites are turning more and more into “apps”. Concepts that make sense for a locally running application are transferred to the web. One of these is the recent addition of “progress bars” to some of Google’s websites that show the loading state of the page.

In this quick tip, we will use the new NProgress jQuery plugin to add a progress bar to a web page. If you’d like to learn more, keep reading!

The NProgress Plugin

NProgress is a jQuery plugin that shows an interactive progress bar on the top of your page, inspired by the one on YouTube. It consists of a global object – NProgress which holds a number of methods that you can call to advance the progress bar. Here is a quick demo of the methods:

(Play with our code editor on Tutorialzine.com)

The plugin github page suggests that you hook up the NProgress.start() function to your $(document).ready() callback and NProgress.done() to $(window).load() which is a very easy way to integrate the plugin. This won’t show the real progress (for that you will have to monitor all the resources that are included in your page and increment the bar manually), however most people won’t notice anyway.

Now that you have a good idea of how NProgress is used, let’s make a more complicated example – a gallery that shows a progress bar while loading images. The bar will correspond to the actual number of images loaded.

The Gallery

As usual, we start off with the HTML markup. This time it is very simple, we only have need a div to hold the photos, and a load button:

index.html

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8"/>
		<title>Quick Tip: Add a Progress Bar to Your Site</title>

		<link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:700" rel="stylesheet" />

		<!-- The Stylesheets -->
		<link href="assets/nprogress/nprogress.css" rel="stylesheet" />
		<link href="assets/css/style.css" rel="stylesheet" />

	</head>

	<body>

		<h1>Gallery Progress Bar</h1>

		<div id="main"></div>

		<a href="#" id="loadMore">Load More</a>

		<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
		<script src="assets/nprogress/nprogress.js"></script>
		<script src="assets/js/script.js"></script>

	</body>
</html>

I am including a custom font from Google Webfonts and two stylesheets in the <head>, and three JavaScript files before the closing </body> tag.

Progress Bar

Progress Bar

Things get more interesting in the jQuery part of the tutorial. Here I am using the Deferred object to show the photos consecutively. This is needed, because we want the photos to download in parallel (which is much faster), but fade into view one after the other. This article is too short to explain how Deferreds work, but you can read through one of these: link, link, link. They are a powerful tool that can simplify asynchronous interactions.

assets/js/script.js

(function($){

	// An array with photos to show on the page. Instead of hard 
	// coding it, you can fetch this array from your server with AJAX.

	var photos = [
		'assets/photos/1.jpg',	'assets/photos/2.jpg',
		'assets/photos/3.jpg',	'assets/photos/4.jpg',
		// more photos here
	];

	$(document).ready(function(){		

		// Define some variables

		var page = 0,
			loaded = 0,
			perpage = 10,
			main = $('#main'),
			expected = perpage,
			loadMore = $('#loadMore');

		// Listen for the image-loaded custom event

		main.on('image-loaded', function(){

			// When such an event occurs, advance the progress bar

			loaded++;

			// NProgress.set takes a number between 0 and 1
			NProgress.set(loaded/expected);

			if(page*perpage >= photos.length){

				// If there are no more photos to show,
				// remove the load button from the page

				loadMore.remove();
			}
		});

		// When the load button is clicked, show 10 more images 
		// (controlled by the perpage variable)

		loadMore.click(function(e){

			e.preventDefault();

			loaded = 0;
			expected = 0;

			// We will pass a resolved deferred to the first image,
			// so that it is shown immediately.
			var deferred = $.Deferred().resolve();

			// Get a slice of the photos array, and show the photos. Depending
			// on the size of the array, there may be less than perpage photos shown

			$.each(photos.slice(page*perpage, page*perpage + perpage), function(){

				// Pass the deferred returned by each invocation of showImage to 
				// the next. This will make the images load one after the other:

				deferred = main.showImage(this, deferred);

				expected++;
			});

			// Start the progress bar animation
			NProgress.start();

			page++;
		});

		loadMore.click();
	});

	// Create a new jQuery plugin, which displays the image in the current element after
	// it has been loaded. The plugin takes two arguments:
	//	* src - the URL of an image
	//	* deferred - a jQuery deferred object, created by the previous call to showImage
	// 
	// Returns a new deferred object that is resolved when the image is loaded.

	$.fn.showImage = function(src, deferred){

		var elem = $(this);

		// The deferred that this function will return

		var result = $.Deferred();

		// Create the photo div, which will host the image

		var holder = $('<div class="photo" />').appendTo(elem);

		// Load the image in memory

		var img = $('<img>');

		img.load(function(){

			// The photo has been loaded! Use the .always() method of the deferred
			// to get notified when the previous image has been loaded. When this happens,
			// show the current one.

			deferred.always(function(){

				// Trigger a custom event on the #main div:
				elem.trigger('image-loaded');

				// Append the image to the page and reveal it with an animation

				img.hide().appendTo(holder).delay(100).fadeIn('fast', function(){

					// Resolve the returned deferred. This will notifiy
					// the next photo on the page and call its .always() callback

					result.resolve()
				});
			});

		});

		img.attr('src', src);

		// Return the deferred (it has not been resolved at this point)
		return result;
	} 

})(jQuery);

The progress bar is incremented with every loaded image by the callback function that listens for the image-loaded custom event. This way the showImage function is free to handle only the loading and displaying of the photos.

With this the gallery progress bar is ready!

Learn AngularJS With These 5 Practical Examples

Learn AngularJS

By now you’ve probably heard of AngularJS – the exciting open source framework, developed by Google, that changes the way you think about web apps. There has been much written about it, but I have yet to find something that is written for developers who prefer quick and practical examples. This changes today. Below you will find the basic building blocks of Angular apps - Models, Views, Controllers, Services and Filters - explained in 5 practical examples that you can edit directly in your browser. If you prefer to open them up in your favorite code editor, grab the zip above.

What is AngularJS?

On a high level, AngularJS is a framework that binds your HTML (views) to JavaScript objects (models). When your models change, the page updates automatically. The opposite is also true – a model, associated with a text field, is updated when the content of the field is changed. Angular handles all the glue code, so you don’t have to update HTML manually or listen for events, like you do with jQuery. As a matter of fact, none of the examples here even include jQuery!

To use AngularJS, you have to include it in your page before the closing <body> tag. Google’s CDN is recommended for a faster load time:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>

AngularJS gives you a large number of directives that let you associate HTML elements to models. They are attributes that start with ng- and can be added to any element. The most important attribute that you have to include in any page, if you wish to use Angular, is ng-app:

<body ng-app>

It should be added to an element that encloses the rest of the page, like the body element or an outermost div. Angular looks for it when the page loads and automatically evaluates all directives it sees on its child elements.

Enough with the theory! Now let’s see some code.

1. Navigation Menu

As a first example, we will build a navigation menu that highlights the selected entry. The example uses only Angular’s directives, and is the simplest app possible using the framework. Click the “Edit” button to see the source code. It is ready for experimentation!

(Play with our code editor on Tutorialzine.com)

In the code above, we are using Angular’s directives to set and read the active variable. When it changes, it causes the HTML that uses it to be updated automatically. In Angular’s terminology, this variable is called a model. It is available to all directives in the current scope, and can be accessed in your controllers (more on that in the next example).

If you have used JavaScript templates before, you are familiar with the {{var}} syntax. When the framework sees such a string, it replaces it with the contents of the variable. This operation is repeated every time var is changed.

2. Inline Editor

For the second example, we will create a simple inline editor – clicking a paragraph will show a tooltip with a text field. We will use a controller that will initialize the models and declare two methods for toggling the visibility of the tooltip. Controllers are regular JavaScript functions which are executed automatically by Angular, and which are associated with your page using the ng-controller directive:

(Play with our code editor on Tutorialzine.com)

When the controller function is executed, it gets the special $scope object as a parameter. Adding properties or functions to it makes them available to the view. Using the ng-model binding on the text field tells Angular to update that variable when the value of the field changes (this in turn re-renders the paragraph with the value).

3. Order Form

In this example, we will code an order form with a total price updated in real time, using another one of Angular’s useful features – filters. Filters let you modify models and can be chained together using the pipe character |. In the example below, I am using the currency filter, to turn a number into a properly formatted price, complete with a dollar sign and cents. You can easily make your own filters, as you will see in example #4.

(Play with our code editor on Tutorialzine.com)

The ng-repeat binding (docs) is another useful feature of the framework. It lets you loop through an array of items and generate markup for  them. It is intelligently updated when an item is changed or deleted.

Note: For a more complete version, see this tutorial, which is based on this one, written with Backbone.js.

4. Instant Search

This example will allow users to filter a list of items by typing into a text field. This is another place where Angular shines, and is the perfect use case for writing a custom filter. To do this though, we first have to turn our application into a module.

Modules are a way of organizing JavaScript applications into self-contained components that can be combined in new and interesting ways. Angular relies on this technique for code isolation and requires that your application follows it before you can create a filter. There are only two things that you need to do to turn your app into a module:

  1. Use the angular.module("name",[]) function call in your JS. This will instantiate and return a new module;
  2. Pass the name of the module as the value of the ng-app directive.

Creating a filter then is as simple as calling the filter() method on the module object returned by angular.module("name", []).

(Play with our code editor on Tutorialzine.com)

Filters follow the Angular.js philosophy – every piece of code that you write should be self-contained, testable and reusable. You can use this filter in all your views and even combine it with others through chaining.

5. Switchable Grid

Another popular UI interaction is switching between different layout modes (grid or list) with a click of a button. This is very easy to do in Angular. In addition, I will introduce another important concept – Services. They are objects that can be used by your application to communicate with a server, an API, or another data source. In our case, we will write a service that communicates with Instagram’s API and returns an array with the most popular photos at the moment.

Note that for this code to work, we will have to include one additional Angular.js file in the page:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>

This includes the ngResource module for easily working with AJAX APIs (the module is exposed as the $resource variable in the code). This file is automatically included in the editor below.

(Play with our code editor on Tutorialzine.com)

Services are entirely self-contained, which makes it possible to write different implementations without affecting the rest of your code. For example, while testing, you might prefer to return a hard-coded array of photos which would speed up your tests.

Further Reading

If you’ve reached this point, you have already grasped the basics of developing with Angular. However, there is much to learn if you want to be a pro. Here is a list of resources which will help you in your quest:

Create a slide-out footer with this neat z-index trick

Slide Out Footer

In this short tutorial, we are going to create an interesting slide-out footer with a bit of CSS. Grab the zip from the download button above, open it in your favorite code editor and read on!

The Idea

The effect we are after, is to give the impression that the page lifts up to reveal a footer, fixed in place. To achieve this:

  • The entire page content, apart from the footer, must reside in a single wrapping element (<div id="main"> in our case). This element will be given a z-index value of 1;
  • The footer must be set to a negative z-index value. It will provide the background color, and make room for the fixed part of the footer (the links and the colorful headings);
  • There must be an element that is set to a fixed positioning with relation to the bottom of the window, and it must have a z-index lower than the #main element, but higher than the footer.

You can learn more about the idea in the following illustration:

The Footer Explained

The Footer Explained

Now let’s see some code!

The HTML

Below you can see the markup of the page. This is basically a regular HTML5 document, in the <head> of which I include a font from Google Webfonts, and the HTML5 shim for older IE browsers.

index.html

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8"/>
		<title>Tutorial: A CSS3 slide-out footer</title>

		<link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:700" rel="stylesheet" />

		<!-- The main CSS file -->
		<link href="assets/css/style.css" rel="stylesheet" />

		<!--[if lt IE 9]>
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
	</head>

	<body>

		<div id="main">

			<h1>A CSS3 slide-out footer.</h1>

		</div>

		<!-- The footer will go here -->

	</body>
</html>

The #main element wraps around the content of the page. As you will see in the next section, we will assign a positive z-index value to it, so that it is rendered above the footer. And here is the markup of the footer itself:

<footer>

	<ul>
		<li>
			<p class="home">Home</p>
			<a class="logo" href="#">Company Name <i>&copy; 2013</i></a>
		</li>
		<li>
			<p class="services">Services</p>

			<ul>
				<li><a href="#">3D modeling</a></li>
				<li><a href="#">Web development</a></li>
				<li><a href="#">Mobile development</a></li>
				<li><a href="#">Web &amp; Print Design</a></li>
			</ul>
		</li>
		<li>
			<p class="reachus">Reach us</p>

			<ul>
				<li><a href="#">Email</a></li>
				<li><a href="#">Twitter</a></li>
				<li><a href="#">Facebook</a></li>
				<li>555-123456789</li>
			</ul>
		</li>
		<li>
			<p class="clients">Clients</p>

			<ul>
				<li><a href="#">Login Area</a></li>
				<li><a href="#">Support Center</a></li>
				<li><a href="#">FAQ</a></li>
			</ul>
		</li>
	</ul>

</footer>

Inside the footer tag, we have an unordered list which holds four groups of links (defined using <li> elements). Each group has a paragraph, which is transformed into a colorful heading for the group, and another <ul> which holds the links. The outermost <ul> will be set to position:fixed, which will make it static with regard to the bottom of the browser window.

The Footer

The Footer

The CSS

As you might guess, this is the place where things get interesting. In the beginning of the tutorial, I mentioned that we are going to work with negative z-indexes to make the footer fixed to the bottom of the screen. There is a very good article that explains z-indexes in detail, which I highly recommend that you read before continuing further. Don’t worry, I will wait.

The first thing we have to do, is to create a stacking context on the body element (any element that contains both the footer and the #main div would work). If you don’t do this, in my experience, the negative z-indexes do not work in mobile Safari, and older IEs. To create a stacking context, we only have to give it a z-index and a position:

assets/css/styles.css

body{
	font:15px/1.3 'PT Sans', sans-serif;
	color: #5e5b64;

	/* Create a page-wide stacking context 
	(so that negative margins work as you expect) */

	position:relative;
	z-index:0;
}

Now all other elements on the page with a z-index value will be stacked according to the body. Next we should assign a z-index to the #main element, so that it covers the footer (otherwise it would always be visible, fixed to the bottom of the window).

#main{
	position:relative;
	z-index:1;

	background-color: #fff;

	background-image:-webkit-radial-gradient(center, circle farthest-corner, #fff, #e2e2e2);
	background-image:-moz-radial-gradient(center, circle farthest-corner, #fff, #e2e2e2);
	background-image:radial-gradient(center, circle farthest-corner, #fff, #e2e2e2);

	padding: 120px 0 600px;
	box-shadow: 0 3px 3px rgba(0,0,0,0.2);
}

A z-index value of 1 is enough to bring the element above all other elements on the page which do not have explicit z-indexes set. In most browsers this is enough to achieve the behavior we are after, but unfortunately mobile Safari has a redrawing issue, which necessitates setting negative z-indexes on the footer. Another thing that we have to do is to set a background on the #main element, otherwise we would see the footer through it.

And here is the footer:

footer{
	height: 245px;
	color:#ccc;
	font-size:12px;

	position:relative;
	z-index:-2;

	background-color:#31353a;

	background-image:-webkit-linear-gradient(top, #31353a, #2f3337);
	background-image:-moz-linear-gradient(top, #31353a, #2f3337);
	background-image:linear-gradient(top, #31353a, #2f3337);
}

I have set a z-index value of -2. Which pushes it behind the #main div. Note that we have to give this element a height, because the UL element that is inside it has a fixed positioning and will not expand its parent to its size.

Next is the UL element inside it, which is fixed to the browser window:

/* Set a width to the outermost UL, center it and fix it to the window */

footer > ul{
	width:960px;
	position:fixed;
	left:50%;
	bottom:0;
	margin-left:-480px;
	padding-bottom: 60px;
	z-index:-1;
}

It is set to a z-index of -1, which causes it to show below the #main element, but above the footer, which is exactly what we want. This concludes the z-index trick, but there are a few more styles that are worth mentioning:

/* The four columns of links */

footer > ul > li{
	width:25%;
	float:left;
}

footer ul{
	list-style: none;
}

/* The links */

footer > ul > li ul li{
	margin-left:43px;
	text-transform: uppercase;
	font-weight:bold;
	line-height:1.8;
}

footer > ul > li ul li a{
	text-decoration: none !important;
	color:#7d8691 !important;
}

footer > ul > li ul li a:hover{
	color:#ddd !important;
}

We have to be extra careful when setting these styles, because the footer contains nested ULs which might get mixed up. To limit the effect of the styles, I am using the CSS child selector >.

Next is the company logo. The image is displayed from a sprite as a :before element.

/* The company logo */

footer a.logo{
	color: #e4e4e4 !important;
	text-decoration: none !important;
	font-size: 14px;
	font-weight: bold;
	position: relative;
	text-transform: uppercase;
	margin-left: 16px;
	display: inline-block;
	margin-top: 7px;
}

footer a.logo i{
	font-style: normal;
	position: absolute;
	width: 60px;
	display: block;
	left: 48px;
	top: 18px;
	font-size: 12px;
	color: #999;
}

footer a.logo:before{
	content: '';
	display: inline-block;
	background: url('../img/sprite.png') no-repeat -19px -70px;
	width: 48px;
	height: 37px;
	vertical-align: text-top;
}

After this, we can style the paragraph elements, which have to be transformed into brightly colored headings for each of the four sections.

footer p{
	width: 90%;
	margin-right: 10%;
	padding: 9px 0;
	line-height: 18px;
	background-color: #058cc7;
	font-weight: bold;
	font-size: 14px;
	color:#fff;
	text-transform: uppercase;
	text-shadow: 0 1px rgba(0,0,0,0.1);
	box-shadow: 0 0 3px rgba(0,0,0,0.3);
	margin-bottom: 20px;
	opacity:0.9;
	cursor:default;

	-webkit-transition: opacity 0.4s;
	-moz-transition: opacity 0.4s;
	transition: opacity 0.4s;
}

footer > ul > li:hover p{
	opacity:1;
}

footer p:before{
	content: '';
	display: inline-block;
	background: url('../img/sprite.png') no-repeat;
	width: 16px;
	height: 18px;
	margin: 0 12px 0 15px;
	vertical-align: text-bottom;
}

Another trick that I used here, is that I set the opacity of the elements to be 0.9 and I defined a transition which will smoothly animate the opacity when it changes. On hover, the opacity is set to 1, which triggers the animation.

Lastly, here are the different color themes, created with the help of a few CSS gradients:

footer p.home{
	background-color: #0096d6;

	background-image:-webkit-linear-gradient(top, #0096d6, #008ac6);
	background-image:-moz-linear-gradient(top, #0096d6, #008ac6);
	background-image:linear-gradient(top, #0096d6, #008ac6);
}

footer p.home:before{
	background-position: 0 -110px;
}

footer p.services{
	background-color: #00b274;

	background-image:-webkit-linear-gradient(top, #00b274, #00a46b);
	background-image:-moz-linear-gradient(top, #00b274, #00a46b);
	background-image:linear-gradient(top, #00b274, #00a46b);
}

footer p.services:before{
	background-position: 0 -129px;
}

footer p.reachus{
	background-color: #d75ba2;

	background-image:-webkit-linear-gradient(top, #d75ba2, #c75496);
	background-image:-moz-linear-gradient(top, #d75ba2, #c75496);
	background-image:linear-gradient(top, #d75ba2, #c75496);
}

footer p.reachus:before{
	background-position: 0 -89px;
}

footer p.clients{
	background-color: #e9ac40;

	background-image:-webkit-linear-gradient(top, #e9ac40, #d89f3b);
	background-image:-moz-linear-gradient(top, #e9ac40, #d89f3b);
	background-image:linear-gradient(top, #e9ac40, #d89f3b);
}

footer p.clients:before{
	background-position: 0 -69px;
}

This makes the headings pretty and colorful, without any images.

We’re done!

I hope that you liked this simple technique. It even works on mobile devices, although you will probably want to write a media query or two so it fits into the form factor better.

Making a Super Simple Registration System With PHP and MySQL

Simple Registration System

Writing a registration system is a lot of work. You have to write code that validates email addresses, sends confirmation emails, provides forgotten password functionality, stores passwords securely, validates input forms and a lot more. Even when you do all of this, users will still be reluctant to register as it involves a lot of effort on their part as well.

In this tutorial, we will make a very simple registration system that doesn’t require or store passwords at all! The result will be easy to modify and embed into an existing PHP website. Read on to find out how it works.

The Idea

Here is how our super simple registration system will work:

  • There will be a combined login/registration form, where users will fill in their emails and hit submit;
  • Upon submission, if an email address is not found in the database, a new user record is created. A random token is generated and sent to the user via email as a clickable link that is only valid for 10 minutes;
  • Clicking the link in their inbox will take them to our site. The system will detect the presence of the token and will log the person in.

Here are the advantages of this approach:

  • No need to store and validate passwords;
  • No need for a password restoration feature, secret questions etc;
  • You can be certain that a person can be reached on the given email address from the first time they login;
  • The registration process is very simple and inviting.

Here are the disadvantages:

  • It is as secure as the user’s email account. If somebody has access to the person’s email, they can login. This is the case with any forgotten password feature, but is a thing to consider;
  • Email is not secure and can be intercepted. Keep in mind that this is also the case with any forgotten password feature or any regular login system that doesn’t use HTTPS to transfer username/password info;
  • Unless you take the time to configure your outgoing email properly, there is a chance that the messages with the login links will hit the spam box;

Given the advantages/disadvantages above, our login system is high on usability but not very high on security, so you should only use it for things like forum registrations, site memberships and services that don’t deal with sensitive information.

Using The Registration System

In case you only wish to use the login system in your site and not to follow the tutorial, here is what you need to do:

  1. First you need to download the zip file above;
  2. In the zip file, find tables.sql. Import it in your database by using phpMyAdmin’s import option. Alternatively you can open the file in a text editor, copy the SQL and execute it;
  3. Open includes/main.php and fill in your database connection details and username/password combo. In the same file, you also have to add an email which will be used as the originating address for the messages sent out by the system. Some web hosts block outgoing email unless it originates from a real email address that is created from their control panel, so put a real address there;
  4. Upload all the files via FTP or other means;
  5. Add this code to every PHP page that you want to make available only after a login;
  6. Have fun!

For the rest of you, who wish to learn how the login system works, read on!

The HTML

The first step is to write the HTML of the login form. The following HTML code resides in index.php. That file also holds the PHP code that handles the form submission and other useful functions of the login system. You will learn more about this in the PHP section.

index.php

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8"/>
		<title>Tutorial: Super Simple Registration System With PHP &amp; MySQL</title>

		<!-- The main CSS file -->
		<link href="assets/css/style.css" rel="stylesheet" />

		<!--[if lt IE 9]>
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
	</head>

	<body>

		<form id="login-register" method="post" action="index.php">

			<h1>Login or Register</h1>

			<input type="text" placeholder="your@email.com" name="email" autofocus />
			<p>Enter your email address above and we will send <br />you a login link.</p>

			<button type="submit">Login / Register</button>

			<span></span>

		</form>

		<!-- JavaScript Includes -->
		<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
		<script src="assets/js/script.js"></script>

	</body>
</html>

In the head section, I’ve included the main stylesheet (it is not presented in the tutorial, so you will have to open it in a code editor to see it). Before the closing body tag, I am including the jQuery library and the script.js file, which we will be writing in the next section.

The Login / Registration Form

The Login / Registration Form

Now let’s write some jQuery!

The JavaScript

jQuery listens for the submit event on the form, calls e.preventDefault() on it, and sends an AJAX request instead. Depending on the response from the server, it shows a message and prevents further submissions.

assets/js/script.js

$(function(){

	var form = $('#login-register');

	form.on('submit', function(e){

		if(form.is('.loading, .loggedIn')){
			return false;
		}

		var email = form.find('input').val(),
			messageHolder = form.find('span');

		e.preventDefault();

		$.post(this.action, {email: email}, function(m){

			if(m.error){
				form.addClass('error');
				messageHolder.text(m.message);
			}
			else{
				form.removeClass('error').addClass('loggedIn');
				messageHolder.text(m.message);
			}
		});

	});

	$(document).ajaxStart(function(){
		form.addClass('loading');
	});

	$(document).ajaxComplete(function(){
		form.removeClass('loading');
	});
});

The .loading CSS class is added to the form while the AJAX request is commencing (this is made possible by the ajaxStart() and ajaxComplete() methods that you can see near the end of the file). This CSS class makes the rotating gif indicator show, and in addition acts as a flag which prevents double submissions (submitting the form while a request is pending). The .loggedIn class is another flag that is set once the email has been sent. It blocks all further form submissions permanently.

Database Schema

Our simple registration system uses two MySQL tables (you can find the SQL code in tables.sql in the downloadable zip). The first table holds the user accounts, and the second holds the login attempts.

Users Table Schema

Users Table Schema

The system doesn’t use passwords, which is reflected in the absence of a password field in the schema. There is a token column, accompanied by a token_validity column. The token is set when a user logs into the system and is sent to the user via email (more on that in the next section). The token_validity is then set to 10 minutes into the future, after which the token becomes invalid.

Every time somebody tries to log in, a new record is written to the second table. As you will see in our PHP code, thanks to this we are able to implement rate limiting by IP address. The limits are 10 login attempts per 10 minutes, and 20 attempts per hour. Anything more than that will result in the IP address being blocked until these limits are met.

Login Attempt Table Schema

Login Attempt Table Schema

In both tables, the IP address is stored as a an integer using the ip2long PHP function.

PHP

Now we are ready to write some PHP code. The main functionality of the registration system is provided by the User class, which you can see below. This class makes heavy use of Idorm (docs), which is a minimal library for working with databases that we’ve used in tutorials before. The User class handles database access, the generation of login tokens and their validation. It exposes a simple interface that makes it easy to include the registration system into your PHP-powered websites.

User.class.php

class User{

	// Private ORM instance
	private $orm;

	/**
	 * Find a user by a token string. Only valid tokens are taken into
	 * consideration. A token is valid for 10 minutes after it has been generated.
	 * @param string $token The token to search for
	 * @return User
	 */

	public static function findByToken($token){

		// find it in the database and make sure the timestamp is correct

		$result = ORM::for_table('reg_users')
						->where('token', $token)
						->where_raw('token_validity > NOW()')
						->find_one();

		if(!$result){
			return false;
		}

		return new User($result);
	}

	/**
	 * Either login or register a user.
	 * @param string $email The user's email address
	 * @return User
	 */

	public static function loginOrRegister($email){

		// If such a user already exists, return it

		if(User::exists($email)){
			return new User($email);
		}

		// Otherwise, create it and return it

		return User::create($email);
	}

	/**
	 * Create a new user and save it to the database
	 * @param string $email The user's email address
	 * @return User
	 */

	private static function create($email){

		// Write a new user to the database and return it

		$result = ORM::for_table('reg_users')->create();
		$result->email = $email;
		$result->save();

		return new User($result);
	}

	/**
	 * Check whether such a user exists in the database and return a boolean.
	 * @param string $email The user's email address
	 * @return boolean
	 */

	public static function exists($email){

		// Does the user exist in the database?
		$result = ORM::for_table('reg_users')
					->where('email', $email)
					->count();

		return $result == 1;
	}

	/**
	 * Create a new user object
	 * @param $param ORM instance, id, email or null
	 * @return User
	 */

	public function __construct($param = null){

		if($param instanceof ORM){

			// An ORM instance was passed
			$this->orm = $param;
		}
		else if(is_string($param)){

			// An email was passed
			$this->orm = ORM::for_table('reg_users')
							->where('email', $param)
							->find_one();
		}
		else{

			$id = 0;

			if(is_numeric($param)){
				// A user id was passed as a parameter
				$id = $param;
			}
			else if(isset($_SESSION['loginid'])){

				// No user ID was passed, look into the sesion
				$id = $_SESSION['loginid'];
			}

			$this->orm = ORM::for_table('reg_users')
							->where('id', $id)
							->find_one();
		}

	}

	/**
	 * Generates a new SHA1 login token, writes it to the database and returns it.
	 * @return string
	 */

	public function generateToken(){
		// generate a token for the logged in user. Save it to the database.

		$token = sha1($this->email.time().rand(0, 1000000));

		// Save the token to the database, 
		// and mark it as valid for the next 10 minutes only

		$this->orm->set('token', $token);
		$this->orm->set_expr('token_validity', "ADDTIME(NOW(),'0:10')");
		$this->orm->save();

		return $token;
	}

	/**
	 * Login this user
	 * @return void
	 */

	public function login(){

		// Mark the user as logged in
		$_SESSION['loginid'] = $this->orm->id;

		// Update the last_login db field
		$this->orm->set_expr('last_login', 'NOW()');
		$this->orm->save();
	}

	/**
	 * Destroy the session and logout the user.
	 * @return void
	 */

	public function logout(){
		$_SESSION = array();
		unset($_SESSION);
	}

	/**
	 * Check whether the user is logged in.
	 * @return boolean
	 */

	public function loggedIn(){
		return isset($this->orm->id) && $_SESSION['loginid'] == $this->orm->id;
	}

	/**
	 * Check whether the user is an administrator
	 * @return boolean
	 */

	public function isAdmin(){
		return $this->rank() == 'administrator';
	}

	/**
	 * Find the type of user. It can be either admin or regular.
	 * @return string
	 */

	public function rank(){
		if($this->orm->rank == 1){
			return 'administrator';
		}

		return 'regular';
	}

	/**
	 * Magic method for accessing the elements of the private
	 * $orm instance as properties of the user object
	 * @param string $key The accessed property's name 
	 * @return mixed
	 */

	public function __get($key){
		if(isset($this->orm->$key)){
			return $this->orm->$key;
		}

		return null;
	}
}

Tokens are generated with the SHA1 algorithm and saved to the database. I am using MySQL’s date and time functions to set the value of the token_validity column to 10 minutes into the future. When validating the token, we explicitly tell the engine that we are looking for a token whose token_validity field has not yet expired. This way we limit how long the login tokens are considered valid.

Notice that I use the __get magic method (docs) near the end of the file to capture property access on the user object. This makes it possible to access the data held in the database as properties: $user->email, $user->token etc. For an example on how to use this class in the next code fragments.

The Protected Page

The Protected Page

Another file that holds useful functionality is functions.php. There we have a number of helper functions that make the rest of the code cleaner.

functions.php

function send_email($from, $to, $subject, $message){

	// Helper function for sending email

	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n";
	$headers .= 'From: '.$from . "\r\n";

	return mail($to, $subject, $message, $headers);
}

function get_page_url(){

	// Find out the URL of a PHP file

	$url = 'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'];

	if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != ''){
		$url.= $_SERVER['REQUEST_URI'];
	}
	else{
		$url.= $_SERVER['PATH_INFO'];
	}

	return $url;
}

function rate_limit($ip, $limit_hour = 20, $limit_10_min = 10){

	// The number of login attempts for the last hour by this IP address

	$count_hour = ORM::for_table('reg_login_attempt')
					->where('ip', sprintf("%u", ip2long($ip)))
					->where_raw("ts > SUBTIME(NOW(),'1:00')")
					->count();

	// The number of login attempts for the last 10 minutes by this IP address

	$count_10_min =  ORM::for_table('reg_login_attempt')
					->where('ip', sprintf("%u", ip2long($ip)))
					->where_raw("ts > SUBTIME(NOW(),'0:10')")
					->count();

	if($count_hour > $limit_hour || $count_10_min > $limit_10_min){
		throw new Exception('Too many login attempts!');
	}
}

function rate_limit_tick($ip, $email){

	// Create a new record in the login attempt table

	$login_attempt = ORM::for_table('reg_login_attempt')->create();

	$login_attempt->email = $email;
	$login_attempt->ip = sprintf("%u", ip2long($ip));

	$login_attempt->save();
}

function redirect($url){
	header("Location: $url");
	exit;
}

The rate_limit and rate_limit_tick functions enforce rate limiting (maximum number of login attempts for a period of time). The login attempts are written to the reg_login_attempt database. These functions are called when handling the submissions of the login form, as you can see from the next fragment.

The code below is taken from index.php and it handles the login form submission. It returns an JSON response, which is handled by the jQuery code we saw in assets/js/script.js.

index.php

try{

	if(!empty($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

		// Output a JSON header

		header('Content-type: application/json');

		// Is the email address valid?

		if(!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
			throw new Exception('Please enter a valid email.');
		}

		// This will throw an exception if the person is above 
		// the allowed login attempt limits (see functions.php for more):
		rate_limit($_SERVER['REMOTE_ADDR']);

		// Record this login attempt
		rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);

		// Send the message to the user

		$message = '';
		$email = $_POST['email'];
		$subject = 'Your Login Link';

		if(!User::exists($email)){
			$subject = "Thank You For Registering!";
			$message = "Thank you for registering at our site!\n\n";
		}

		// Attempt to login or register the person
		$user = User::loginOrRegister($_POST['email']);

		$message.= "You can login from this URL:\n";
		$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

		$message.= "The link is going expire automatically after 10 minutes.";

		$result = send_email($fromEmail, $_POST['email'], $subject, $message);

		if(!$result){
			throw new Exception("There was an error sending your email. Please try again.");
		}

		die(json_encode(array(
			'message' => 'Thank you! We\'ve sent a link to your inbox. Check your spam folder as well.'
		)));
	}
}
catch(Exception $e){

	die(json_encode(array(
		'error'=>1,
		'message' => $e->getMessage()
	)));
}

On a successful login or registration, the code above will send out an email to the person with a login link. The token is made available as the tkn $_GET variable in the generated URL.

Visiting the login link will trigger this code:

index.php

if(isset($_GET['tkn'])){

	// Is this a valid login token?
	$user = User::findByToken($_GET['tkn']);

	if($user){

		// Yes! Login the user and redirect to the protected page.

		$user->login();
		redirect('protected.php');
	}

	// Invalid token. Redirect back to the login form.
	redirect('index.php');
}

Calling $user->login() will create the needed session variables, so that subsequent views of any page of the site will keep the person logged in.

Logging out of the system is handled similarly:

index.php

if(isset($_GET['logout'])){

	$user = new User();

	if($user->loggedIn()){
		$user->logout();
	}

	redirect('index.php');
}

At the end of the code, I am redirecting to index.php again, so that the ?logout=1 parameter in the URL is removed.

Our index.php file needs another protection – we don’t want already logged in people to see the form. For this purpose, we are going to use the $user->loggedIn() method:

index.php

$user = new User();

if($user->loggedIn()){
	redirect('protected.php');
}

Lastly, here is how to protect a page of your site and make it available only after a login:

protected.php

// To protect any php page on your site, include main.php
// and create a new User object. It's that simple!

require_once 'includes/main.php';

$user = new User();

if(!$user->loggedIn()){
	redirect('index.php');
}

After this check, you can be sure that the user has been successfully logged in. You will also have access to the data stored in the database as properties of the $user object. To output the user’s email and their rank, use this code:

echo 'Your email: '.$user->email;
echo 'Your rank: '.$user->rank();

rank() is a method here, because the rank column in the database normally contains numbers (0 for a regular user, 1 for an administrator) and we need to transform these into rank names, which is done in that method. To turn a regular user into an administrator, simply edit their record from phpMyAdmin (or a database management program of your choice). Being an administrator will not give him any additional abilities – it will simply report him as such. It is up to your code to give special powers to administrators.

We’re Done!

With this our super simple registration system is complete! You can easily use it in an existing PHP website and modify it any way you like.

8 Tips For Promoting Your Dev Skills

Promoting Your Dev Skills

Many front-end developers possess the creative and technical skills that clients are looking for, but don’t get noticed because they don’t have much exposure or reputation to demonstrate to potential clients. Some carry the idea that their area of work is in such high demand that clients will simply come to them – but this is rarely the case.

A great way to get your name out there, build a reputation, and accumulate a list of clients is to market your specific skills. This is not only an excellent technique for freelancers, but it could also be what sets you apart from competition fighting for a particular job. As a developer, you may not know where to even begin in the process of marketing yourself. Follow these tips to increase your chances of attracting clients by effectively portraying your strengths.

1. Find Your Niche

It’s tempting to spread yourself thin and learn a little bit of everything so you can say that you can do it all, but you’ll benefit more by becoming an expert in one niche (you can’t be everything to everyone, after all). Narrow your interests or skills to something like ecommerce, blog, or mobile app design. Become an expert by learning the ins and outs of that area, and then working and experimenting with it. You’ll begin to build the groundwork of a good portfolio, and it will make reaching potential clients a less daunting endeavor. Your leadership in a specific field will increase your demand, leading to a flow of work that allows you to choose the best projects for you.

2. Get Published

As a way to help establish your expertise, consider writing an article or case study about your niche skill set. You can start by posting helpful articles on your blog or website to interest readers, and then start submitting longer pieces to other reputable sites like SmashingMagazine or e-book publishing networks. Even publishing a book as HTML on your site, like Addy Osmani does, can do wonders for your reputation. The community awards valuable resources with its full attention. This can result in invitations for speaking at conferences, networking with other community members and consultancy work.

3. Participate In Online Communities

You can also build your reputation by investing in communities like Stackoverflow and Quora. Not only does it allow you to connect with other developers, but it also publicly showcases your ability to solve problems. And through open source software platforms like Github, you can publish your projects and invite a host of other community collaborators. Having a strong foundation within these communities can be invaluable when communicating your expertise and building your network.

4. Create A Microsite

Single page websites are the perfect platform to show off your skills. Especially if you design one that focuses on a not-for-profit purpose that is creative, beautifully designed and contains interesting content. These are the sites that are more likely to be shared by users, which is a great way of getting free and quick exposure. Don’t be afraid to go crazy with features like parallax scrolling, unconventional grids and sliding effects to adequately showcase your abilities. On the flip side though, while it’s important to showcase the breadth of your skills, often time’s simple pages, like this iPod visualization or this one, can go a long way. This is a great way to let potential clients (or your interviewer) not simply look at, but interact with something you’ve created.

This home security guide for SimpliSafe, chock full of creativity and quality content, is a great example of a project that you can have people interact with. This one takes the user through the process of securing a home, enhanced with a clever comparison to a castle defense system and imaginative parallax scrolling.

Layered Defense

Layered Defense

5. Develop An Online Tool

If you’ve ever found yourself wishing there was a tool to serve a specific purpose to aid you in your work, consider making one yourself. Patrons will surely be amazed by the fact that you have developed a tool or app that other developers use. Sometimes the simplest concepts can be the most helpful, so simplify your ideas to make them look effortless.

CodePen is an example of how online tools can be immensely helpful to front-end developers. Use this in-browser code editor as inspiration for the tools you create.

CodePen

CodePen

6. Create Free Resources or Plugins

Another effective direction to gear your personal projects is to create free, downloadable resources for developers through the web. Consider enabling users to give feedback on their performance, so you can show clients that you’re dedicated to following through and improving on your projects. You can even submit them to sites like Design Instruct to gain more published exposure.

This UI designer created a Sketching and Wireframing Kit to provide a convenient and useful resource for UI and wireframing elements to his readers. Easily accessed right from his website, he offers multiple download formats and an opportunity for user feedback.

Wireframing Kit

Wireframing Kit

7. Use Social Networking

Social networking is arguably the most efficient means of free advertising. Since it’s fueled by users and their online word-of-mouth, your name and work can easily spread, which is why this is a marketing strategy worth your time. You can use sites like Facebook, Twitter and Pinterest to contribute high quality posts to the public, and link them back to your blog, which should narrow its content to further fit your niche audience. Internet users and clients will likely expect you to have accounts on all these networking sites, but make it easier for them to check them out through social media links on your blog and/or website, writing pieces and all other marketing elements you create.

8. Connect All Your Work

By linking all of your work and media sites to each other and keeping all your content consistent, you transform yourself from a freelancer (or job applicant) to a brand, which is much easier to market. You’ll build a following of readers and clients that can give feedback and recommendations to others, while your client base continues to grow. The work that you have developed to show to potential clients will put you that much further ahead of your competition, and you can anticipate the demand for your work to multiply. So instead of waiting for clients to come to you, use these assertive strategies to reveal your skills.

50 Must-have plugins for extending Twitter Bootstrap

featured_4

You most certainly know about Twitter Bootstrap - the popular front end framework for building websites and apps. It favors simple, responsive design, and comes bundled with a sensible default stylesheet, a number of useful jQuery plugins and an icon set. Although it doesn’t come with much else, Bootstrap is very extensible. In this article, you will find a collection of 50 must-have plugins you should know about for effective development with the framework. Let’s begin!

Collections of Bootstrap Enhancements

We will start off with two collections of Bootstrap plugins that are the perfect companions to the framework.

Fuel UX

Fuel UX is an incredible collection of enhancements to Twitter Bootstrap. All the controls are clean and lightweight, and they fit naturally into the bootstrap look and feel. The collection includes controls like datagrids, custom select boxes, spinners, trees, multi-step form wizards and more.

Website | Github

Fuel UX

Fuel UX

Jasny

Jasny is another collection of useful interface components for bootstrap. It features controls like input masks, file upload buttons, icons, additional form styles and more. You can either get a version of bootstrap with all the changes integrated, or you can download them separately as plugins.

Website | Github

Jasny Bootstrap

Jasny Bootstrap

Galleries

It is worth noting that you can use any regular jQuery plugin with your bootstrap-powered website. This means that any of the galleries from our jQuery plugin collection will work perfectly fine. What these plugins won’t have though, is bootstrap’s design language and way of doing things. For this reason, check out these three plugins specifically created with bootstrap in mind:

Bootstrap Lightbox

Bootstrap does include a carousel, but it falls short when you need to show a photo in a lightbox. This is where the simple Bootstrap Lightbox plugin comes into play. All you need to do is add the required HTML to the page, and you get a pretty and responsive lightbox with an optional caption.

Website | Github

Bootstrap Lightbox

Bootstrap Lightbox

Simple Lightbox

Simple Lightbox is another lightbox plugin that is simpler that the one above. It requires only that you add a data attribute to the image and to initialize the plugin.

Website

Simple Lightbox

Simple Lightbox

Bootstrap Image Gallery

Bootstrap Image Gallery is a complete gallery solution for bootstrap. After you include the needed files in your page, you get a grid of images which open in modal windows. The gallery can also optionally go into fullscreen mode. Note that there is now an improved version of this plugin which drops the Bootstrap requirement, so you can use it in any project.

Website | Github

Bootstrap Image Gallery

Bootstrap Image Gallery

Dialogs and Notifications

Bootstrap comes with a good modal window implementation out of the box. These plugins make it even better.

Bootbox.js

Bootbox.js is a small JavaScript library that automates the process of creating bootstrap dialogs. It creates the needed markup for you, so all you have to do to trigger a bootstrap dialog is to call a function. It mimics the built-in browser dialogs like alert, confirm and prompt.

Website | Github

Bootbox.js

Bootbox.js

Bootstrap Modal

Bootstrap Modal extends the default bootstrap modal class. It makes the default dialogs responsive and adds the ability to load their content via AJAX automatically for you.

Website | Github

Bootstrap Modal

Bootstrap Modal

Bootstrap Growl

Bootstrap Growl is a jQuery plugin which turns Bootstrap’s notifications into pretty Growl-like alerts. Notifications can be heavily customized; you can choose the position on the screen, dimensions offsets and time to fade out.

Github

Bootstrap Growl

Bootstrap Growl

Bootstrap Notify

Bootstrap Notify is a user-friendly extension to bootstrap notifications. Like the growl plugin above, here you can also heavily customize every aspect of the notifications and where they are shown.

Website | Github

Bootstrap Notify

Bootstrap Notify

Forms

Forms are the necessary evil of web development. They may be tedious and boring to create and to fill in, but they occupy a very important place in our online interactions. Bootstrap brings a long list of enhancements to forms in terms of usability and presentation. It may not offer much else, but the plugins in this section do a great job at changing that.

Bootstrap Form Helpers

Bootstrap Form Helpers is an indispensable collection for enhancing web forms. It comes with 12 custom jQuery plugins that give you everything from date and time pickers, font lists, timezone, language and country fields and more.

Website | Github

Bootstrap Form Helpers

Bootstrap Form Helpers

Bootstrap Tags

Bootstrap Tags is a plugin which can enhance your search boxes by presenting the search terms as tags. The plugin also supports filters, placeholders, popovers and autosuggest as well as a full set of callback functions so you can hook it up with your code. Similar plugins are Tags Manager and Bootstrap Tag.

Website | Github

Bootstrap Tags

Bootstrap Tags

Bootstrap Switch

No mobile interface is complete without a iOS-like switch control, and Bootstrap Switch gives you a perfect implementation that fits nicely into the Bootstrap design language. You can customize the size of the control and the colors by assigning class names to the element. The plugin is really simple to set up, as it wraps around an existing checkbox.

Website | Github

Bootstrap Switch

Bootstrap Switch

Bootstrap Markdown

I’ve mentioned markdown on Tutorialzine before (we even made a lightweight blog system with it ). Bootstrap markdown makes it possible to add markdown editing functionality seamlessly to your projects.

Website | Github

Bootstrap Markdown

Bootstrap Markdown

Bootstrap Maxlength

Bootstrap Maxlength is a neat little plugin which detects the HTML maxlength property of a textfield, and displays an interactive counter of the remaining characters. It is a great addition to text boxes and text areas.

Website | Github

Bootstrap Maxlength

Bootstrap Maxlength

Bootstrap Select

Bootstrap favors native browser controls, which is the reason it doesn’t expose any customization options for them. However, in some projects it is useful to have customizable controls like select boxes, which is exactly what Bootstrap Select does. This plugin gives you a pretty and customizable select box which looks great in your page. For an alternative try with SelectBoxIt, or one of the other well-known plugins like Select2 or Chosen.

Website | Github

Bootstrap Select

Bootstrap Select

Bootstrap Multiselect

And for select inputs without the multiple attribute, you can use Bootstrap Multiselect. The plugin creates an intuitive interface for using select inputs with the multiple attribute present. Instead of a select, a bootstrap button will be shown as a dropdown menu containing the single options as checkboxes.

Website | Github

Bootstrap Multiselect

Bootstrap Multiselect

Bootstrap WYSIHTML5

Bootstrap WYSIHTML5 is a beautiful rich text editor for bootstrap that comes in the form of an easy to embed JavaScript plugin. It gives you only basic functionality, but this will be fine for 90% of the use cases. For a bit more advanced editor, try this one or the insanely powerful TinyMCE.

Website | Github

Bootstrap WYSIHTML5

Bootstrap WYSIHTML5

Bootstrap Form Wizard

It is a good practice to split long forms into smaller, contextually similar chunks. This makes them a bit easier to handle. The Bootstrap Form Wizard does that for you and more.

Website | Github

Bootstrap Form Wizard

Bootstrap Form Wizard

jqBootstrapValidation

jqBootstrapValidation is a plugin that makes it easy to validate your Bootstrap forms. It is easy to include into your project and all the validation rules are described as data attributes on the input elements. If you need an alternative plugin, take a look at nod.

Website | Github

jqBootstrapValidation

jqBootstrapValidation

jQuery File Upload

jQuery File Upload is a very powerful and versatile file uploading plugin. See our tutorial about it here. The plugin is not strictly for bootstrap, but all the examples of their homepage use the frontend framework extensively.

Website | Github

jQuery File Upload

jQuery File Upload

Bootstrap Tag Autocomplete

Bootstrap Tag Autocomplete is a library which adds twitter and facebook-like mentions to your content editable text areas. It takes an array of available completions and inserts them as nodes in the text area on a match.

Website | Github

Bootstrap Tag Autocomplete

Bootstrap Tag Autocomplete

Date and Time Pickers

Your web application probably requires dates to be formatted in a specific way, and expecting people to manually type them in is a road that can only lead to frustration. The better approach is to have a widget which lets users simply click or tap on the date they need. The plugins in this category add such functionality to your Bootstrap forms.

Daterangepicker

Daterangepicker is a plugin for Bootstrap that is the perfect addition to your reports page. It lets users choose preset time periods like the last 7 or 30 days (you can define your own presets) and they can also choose an arbitrary time intervals. You only need to pass a few callback functions when instantiating the plugin, and you are ready to go. Check out a tutorial where we used this plugin to update a chart.

Website | Github

Daterangepicker

Daterangepicker

Bootstrap Timepicker

Bootstrap Timepicker is a pretty and touch friendly plugin that lets you turn text fields into time selection controls. It doesn’t have support for dates, but for that you can use one of the next plugins.

Website | Github

Bootstrap Timepicker

Bootstrap Timepicker

Clockface

Clockface is an alternative plugin to the one above. It presents the hours and minutes as text labels in a circle. While it is a bit ugly for my taste, I give it points for originality.

Website | Github

Clockface

Clockface

Bootstrap Datetime

Bootstrap Datetime Picker is a fully featured plugin that lets you turn a text field into a handy date and time picker control. The plugin is pretty and fits nicely with the framework’s design language. It is also fairly easy to customize with CSS. For an alternative check out this plugin.

Website | Github

Bootstrap Datetime

Bootstrap Datetime

Bic_Calendar

Bic_Calendar is a simple calendar widget that can show events loaded through AJAX. An example PHP script is included that outputs the events as a JSON object. The events are then displayed on the calendar and shown in a popup.

Website | Github

Bic_Calendar

Bic_Calendar

Color Pickers

Entering colors is another area that users need help with. You can’t simply think of a color and write down its hex value – you need to visualize it in some way. The plugins listed here help you alleviate this problem by creating color picker controls and swatches.

Pick a Color

Pick a Color is a bootstrap addon that shows an advanced color picker. You can choose colors by modifying one of the presets, by choosing a previously saved one, or generating a color by modifying the hue, saturation and lightness components.

Website | Github

Pick a Color

Pick a Color

Colorpicker for Bootstrap

Colorpicker for Bootstrap is a more traditional color picker – you get a Photoshop-like widget that lets you choose the main color and specific hues. I personally find this easier to use than the above plugin.

Website | Github

Colorpicker for Bootstrap

Colorpicker for Bootstrap

Color Palette

Color Palette is a Bootstrap plugin that displays a grid of color swatches when a text field is focused. The plugin is easy to integrate with your bootstrap project.

Website | Github

Color Palette

Color Palette

Tables

Bootstrap already offers basic table styles that do a great job with simple data. However, what if you’d like that data to be sortable, searchable and presentable on multiple pages? Read on.

Tablecloth

Tablecloth is a plugin that makes your tables pretty. It comes with a number of built-in styles, and it uses plugins like tablesorter internally to make the data in your tables sortable.

Website | Github

Tablecloth

Tablecloth

Data Tables

Data Tables is another table enhancing addon for Bootstrap. This plugin not only makes your tables sortable, but it also makes use of the framework’s pagination controls and makes the data searchable.

Website

Data Tables

Data Tables

Interface Enhancements

This section contains various plugins that enhance the interface of your web app.

jQuery Bootpag

jQuery Bootpag is an enhanced bootstrap pagination plugin. It is very easy to set up – you only have to pass a callback function and listen for the page event. Inside that function, you can update the container element with the content that you need.

Website | Github

jQuery Bootpag

jQuery Bootpag

Tocify

Tocify is a table of contents plugin. It scans your page on DOMReady, looking for headings, and creates a Bootstrap – styled table of contents dynamically.

Website | Github

Tocify

Tocify

Bootstrap Link Preview

Bootstrap Link Preview is a JavaScript library offering a Facebook-like preview for URLs. It is very simple to use and weighs just a few kilobytes. To work around the same origin policy it depends on a PHP script though.

Website | Github

Bootstrap Link Preview

Bootstrap Link Preview

Tab drop

Tab drop is a neat plugin that hides your tabs in a dropdown if they don’t fit in a single row. This can come handy when designing responsive sites that need to work on small screens.

Website

Tab drop

Tab drop

Flippant.js

Flippant.js is a tiny plugin that lets you flip elements to reveal further content with a smooth CSS transition. You can put any content on the back side – simply pass it as an argument to the function call.

Website | Github

Flippant.js

Flippant.js

Hover Dropdown

Another interface enhancement for Bootstrap. With the Hover Dropdown plugin you can activate the framework’s dropdowns on hover in addition to click. This can make for a better user experience with your site.

Website | Github

Hover Dropdown

Hover Dropdown

Social Buttons

Social Buttons is a collection of pretty social networking buttons built with Bootstrap and Font Awesome. This makes them very easy to scale and style.

Website | Github

Social Buttons

Social Buttons

Bootstro.js

Bootstro.js is a bootstrap plugin that lets you build a guided tour for new users. A tour consists of tooltips and overlays which explain the functions of your app. The plugin has plenty of options and callbacks, so it is easy to hook up with the rest of your code. For an alternative, checkout Bootstraptour.

Website | Github

Bootstro.js

Bootstro.js

AJAX

The Bootstrap extensions in this section handle inline editing of content with automatic syncing with your server, extend the framework with AJAX bindings and more.

X-editable

X-editable is a library that enhances Bootstrap with inline editing capability. Clicking an element that is set to be editable, will open up a bootstrap popup with a text field and buttons. In addition, it supports editing inline and has many different types of text controls including rich text editors and date pickers. On a successful edit, the plugin sends an AJAX request to your server.

Website | Github

X-editable

X-editable

Eldarion AJAX

With Eldarion AJAX you can extend bootstrap with automatic AJAX request handling. Simply add the ajax class to the button or link you wish to enhance, and the plugin will do the rest. It will send a request and replace the contents of the element with the response from the server. You can also submit forms in the same manner.

Website | Github

Eldarion AJAX

Eldarion AJAX

Typeahead

Typeahead is a library by twitter that offers a fast and fully featured autocomplete control for your site. It supports fetching autocomplete data via AJAX, caching, rate limiting and more. The most common selections are displayed as hints. The library is not dependent on bootstrap, but it can be easily integrated with it.

Website | Github

Typeahead

Typeahead

Conclusion

Bootstrap is a valuable addition to your web development toolbox. Knowing your way around the framework will let you build usable and responsive interfaces with ease. And with the plugins presented here, you can add advanced functionality that fits nicely with the rest of your site.