Link Dump – January 5, 2013 Edition

The holidays are over and because I haven’t published anything last week I made this weeks link dump extra special by putting in 30 links to articles, news and resources on web development. Enjoy!

33 fantastic Chrome extensions | Feature
http://www.netmagazine.com/features/33-fantastic-chrome-extensions

The Web Is Growing Up
http://io.brewerlogic.com/the-web-is-growing-up/

OOCSS + Sass = The best way to CSS by Ian Storm Taylor
http://ianstormtaylor.com/oocss-plus-sass-is-the-best-way-to-css/

Does JavaScript need classes? | NCZOnline
http://www.nczonline.net/blog/2012/10/16/does-javascript-need-classes/

It’s a Trap! 10 Interview Questions Designed To Trick You
http://smarterer.com/blog/2012/10/16/its-a-trap-10-interview-questions-designed-trick-you/

How to Use Git With FTP
http://net.tutsplus.com/tutorials/tools-and-tips/how-to-use-git-with-ftp/

CSS3 Regions and Flow
http://www.inserthtml.com/2012/10/css3-regions-flow

Master the new CSS layout properties | Tutorial
http://www.netmagazine.com/tutorials/master-new-css-layout-properties

The 4Cs: A Code Review Mnemonic
http://blog.mojotech.com/post/33300886323/the-4cs-a-code-review-mnemonic

The Elements of Comment Style
http://www.altdevblogaday.com/2012/09/20/the-elements-of-comment-style-2/

codylindley/frontend-tools GitHub
https://github.com/codylindley/frontend-tools

❍ IcoMoon
http://icomoon.io/#home

The What, Why and How of Data URIs in Web Design
http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/the-what-why-and-how-of-data-uris-in-web-design/

More CSS Secrets: Another 10 things you may not know about CSS
http://lea.verou.me/more-css-secrets/#slide4

25 Useful Books For Web Designers And Developers
http://www.hongkiat.com/blog/books-for-designers-developers/

Top 10 PHP Security Vulnerabilities
http://phpmaster.com/top-10-php-security-vulnerabilities/

PHP Master | Spooky Scary PHP
http://phpmaster.com/spooky-scary-php/

So you want to be a Rock Star Developer? Maybe you should reconsider.
http://programmers.blogoverflow.com/2012/10/so-you-want-to-be-a-rock-star-developer-maybe-you-should-reconsider/

The Real Beauty of CSS3 Box Shadows | Code Theory
http://codetheory.in/the-real-beauty-of-css3-box-shadows/

An Introduction to Media Queries
http://www.briangardner.com/media-queries/

Emmet Documentation
http://docs.emmet.io/

The Problem With Style Guides
http://hellogeri.com/blog/view/the_problem_with_style_guides

Front-End Engineering
http://bitly.com/bundles/dmosher/1

SMACSS and SASS – The future of stylesheets
http://railslove.com/blog/2012/03/28/smacss-and-sass-the-future-of-stylesheets/

JavaScript APIs youve never heard of (and some you have)
http://www.slideshare.net/nzakas/javascript-apis-youve-never-heard-of-and-some-you-have

Hot in web standards: September/October 2012 | Feature
http://www.netmagazine.com/features/hot-web-standards-septemberoctober-2012

Backbonification: migrating a large JavaScript project from DOM spaghetti to Backbone.js
http://www.ofbrooklyn.com/2012/11/13/backbonification-migrating-javascript-to-backbone/

Front End Development Guidelines
http://taitems.github.com/Front-End-Development-Guidelines/

Mohit Seth: Best practices in javascript / jQuery
http://blog.sethmohit.com/2012/08/best-practices-in-javascript-jquery.html

Understanding JavaScript Closures | JavaScript, JavaScript
http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/

The Problem with Style Guides
http://hellogeri.com/blog/view/the_problem_with_style_guides

13 Conference Videos that Every Developer Should Watch

Here are some of the videos from web developer conferences that I think every developer should watch.

Google IO 2012 – SQL vs NoSQL: Battle of the Backends (Ken Ashcraft, Alfred Fuller)

Google IO 2012 – Chrome Developer Tools Evolution (Sam Dutton, Pavel Feldman)

Google IO 2012 – The Web Can Do That! (Eric Bidelman)

Google IO 2012 – New Web Tools and Advanced CSS HTML5 Features from Adobe and Google (Alex Danilo, Vincent Hardy, Christian Cantrell)

Google IO 2012 – High Performance HTML5 (Steve Souders)

Google IO 2011 – Learning to Love JavaScript (Alex Russell)

Fluent 2012 – Javascript Development Workflow of 2013 (Paul Irish)

Google IO 2012 – Better Web App Development Through Tooling (Paul Irish)

Front Trends 2012 – Breaking Good Habits (Harry Roberts)

Breaking Good Habits – Harry Roberts from Front-Trends on Vimeo.

Fluent 2012 – Your Script Just Killed My Site (Steve Souders)

What We Don’t Know (Chris Coyier)

JS Conf US 2012 – JavaScript Tooling (Paul Irish)

[blip.tv http://blip.tv/play/g_MngvbfHwI?p=1 width=”560″ height=”315″]

Front Trends 2012 – How Browsers Work Internally (Tali Garsiel)

How browsers work internally – Tali Garsiel – Front-Trends 2012 from Front-Trends on Vimeo.

Playing with Sugar.js

Introduction

Did you ever need the functionality to get the first 2 items in a JavaScript array? Or get the average of all the items? Or maybe sort the items in the array by its length? Or functions for determining if a string has Japanese or Greek characters? Or maybe formatting dates into their string versions? Or getting the exact date from today after 5 months?
Did you ever wish for JavaScript to have these functions built-in to it and that you could easily call it without having to create your own functions?

Now you can have all of these functions by using a library called Sugar.js. It’s sort of like Underscore.js that serves as a utility belt for JavaScript. Most of the functions that you wished JavaScript have for manipulating Strings, Arrays, Dates, and Objects is already included in Sugar.js.

In this article I’ll be giving you an introduction on Sugar.js, what sort of things you can do with it, the functions that you can use for manipulating Strings, Arrays and Objects. I’ll also show you how to write the equivalent of those Sugar.js functions in plain JavaScript function and extending the JavaScript Prototype.
So yeah, let’s get started and play with it. I’ve already linked each of the functions to a fiddle so that you can play with it. I didn’t have any luck including fiddles for the Sugar.js scripts so you might as well play on the Sugar.js site. You can actually edit the sample scripts and see the output right away.

Arrays

Getting a specified number of items from an array starting from index 0.

Sugar.js:

[4, 5, 6, 7].first(2) //output: [4, 5]

Plain JavaScript Function:

function get_first(array, num){
   var new_array = [];

   for(var x = 0; x<num; x++){
      new_array[x] = array[x];
   }
   return new_array;
}
//call: get_first([4,5,6,7], 2)
//output: [4,5]

Extending Array Prototype:

Array.prototype.get_first = function(num){
   var new_array = [];

   for(var x = 0; x<num; x++){
      new_array[x] = this[x];
   }
   return new_array;
}
//call: [1,2,3].get_first(2)
//output: [1,2]

There’s also a function for getting the average from the specified array.
Sugar.js:

   [1,2,3].average(); //output: 2

Plain JavaScript Function:

function get_average(array){
   var r_length = array.length;
   var total = 0;
   for(var x in array){
      total = total + array[x];
   }
   return parseFloat(total) / parseFloat(r_length);
}
//call: get_average([1,2,3]);
//output: 2

Extending Array Prototype:

Array.prototype.get_average = function(){
   var r_length = this.length;
   var total = 0;
   for(var x in this){
      total = total + this[x];
   }
   return parseFloat(total) / parseFloat(r_length);
}
//call: [1,2,3].get_average()
//output: 2

There’s also a function for getting the max and min values from an array.
Sugar.js:

[4, 5, 6].max() //output: 6
[10, 2, 22].min() //output: 2

Plain JavaScript Function:

function sort(array, sortby){
   if(sortby == 'ASC'){
      var val = array.sort(function(a, b){
         return b + a;
                })[0]
   }else if(sortby == 'DESC'){
      var val = array.sort(function(a, b){
         return b - a;
                })[0]
   }
   return val;
}
//call: sort([4,5,22,33,1], 'ASC')
//output: 1
//call: sort([4,5,22,33,1], 'DESC')
//output: 33

Extending Array Prototype:

Array.prototype.max = function(){
   return this.sort(function(a, b){
      return b - a;
                   })[0]
}
//call: [44,50,24,16].max()
//output: 50

 

Array.prototype.min = function(){
   return this.sort(function(a, b){
   return b + a;
                    })[0]
}
//call: [50,2,1,3,16].min()
//output: 1

Numbers

There are also functions used for manipulating numbers. Remember that numbers are delicate so don’t call functions for numbers like the way you do when calling string functions or else you’ll really get a nasty error. If you don’t know what I mean try executing a Sugar.js function normally:

6.isEven() //output: SyntaxError: Unexpected token ILLEGAL

Here’s what you can do to avoid getting errors the first method is by enclosing your number in parentheses and then call the function as you normally would:

(4).isEven() //output: true

Second method is by using bracket notation:

4['isEven']() //output: true

Plain JavaScript Function:

function even(num){
   return num % 2 === 0;
}
//call: even(4)
//output: true

 

function odd(num){
   return num % 2 !== 0;
}
//call: odd(4)
//output: false

Extending the Number Prototype:

Number.prototype.even = function(){
   return this % 2 === 0;
}
//call: 30['even']()
//output: true

 

Number.prototype.odd = function(){
return this % 2 !== 0;
}
//call: 30['odd']()
//output: false

Strings

There are also string functions used for manipulating string. Most of the functions that is included in Sugar.js are already present in plain JavaScript so I won’t use them as examples.

The first function is used for getting a part of a string from the specified index. Remember that programming languages are zero-indexed so you will need to use 0 if you want to get the 1st character, 1 if you want to get the 2nd character and so on.

Sugar.js

'super_duper_cool'.from(12) //output: cool

<strong><span style=”font-size: small;”>Plain JavaScript Function:</span></strong>

function from(str, frm){
   var last = str.length;
   return str.substr(frm, last);
}
//call: from("javascriptiscool", 12)
//output: cool

Extending the String Prototype:

String.prototype.start_from = function(frm){
   var last = this.length;
   return this.substr(frm, last);
}
//call: "youareawesome".start_from(3)
//out: areawesome

Conclusion

Sugar.js is a really nice way to extend the functions that are already built in to JavaScript. If you’re looking for a quick and dirty solution for your JavaScript problems Sugar.js is a way to go. It’s also useful if you want to save time in writing functions from scratch. But if you’re still a JavaScript beginner just like me I would recommend that you go ahead and check out the functions in Sugar.js or Underscore.js and see if you can build those functions from scratch just like what I did here. You could learn a lot in writing JavaScript code by simply doing that.

Resources

Introduction to LocalStorage and Store.js

Introduction

Have you used localStorage to store values in the browser persistently? Have you used it to store integer values only to find out that it actually only stores values as strings? In this article I’m going to walk you through a library called store.js which allows you to use the power of localStorage while still giving you the functionality that you expect (eg. Storing values in their original data types).

But before we play with Store.js I’m gonna give you a quick introduction on LocalStorage. LocalStorage allows you to store data locally (in your computer). It’s also a persistent storage which means that the data that you store using LocalStorage will actually stay there even after a power-interruption or you accidentally closed your browser. Here are the things you need to remember when using LocalStorage:

  • It’s data that is stored browser-wide which means that the data is not linked to a single browser tab. If that’s a bit unclear to you try storing a new item in the localStorage, open a new tab and go to google.com. You will still get the item that you have set even if you didn’t set the item on the same tab.
localStorage['name'] = 'kyokasuigetsu'
localStorage['name']; //output: kyokasuigetsu
  • There are two ways you can store localStorage item. The first one is by using the bracket notation, and the second one is the dot notation. Just like how you set or get values for individual properties in a JavaScript object.
localStorage['speed'] = '10,000 miles per hour
localStorage.setItem('speed', '10,000 miles per hour')
  • It can only store string values. To demonstrate this let’s try storing an integer value in localStorage and add a value into it. Go ahead and try it using the console in Chrome developer tools or see the example below. You’ll see that the output is 21 instead of the value that were expecting which is 3. This means that any other data type is converted to string (stringified) when stored in localStorage which isn’t very nice since you have to convert localStorage items to their proper data type in order to make sense out of them.
localStorage.setItem('number', 2)
localStorage.getItem('number') + 1 //output: 21

LocalStorage only stores string values that’s why some cool people creates libraries like store.js to make localStorage awesome.

To use store.js you have to include it on the page where you want to use it.

<script src="store.js></script>

Items in store.js are stored in groups called stores. Here’s how to create a new store. It’s like creating a new object of the Store class.

var items = new Store('items')

You then get to store items inside it:

items.set('number', 2)

We can also get the item that we have just set and add 1 to it. Now you’ll see that the output is 3 which means that the number 2 wasn’t converted to a string value.

items.get('number') + 1 //output: 3

Ok now were done with an example I might as well show you the different data types which you can store using store.js. I have just showed you how to store integer values. Everything is pretty much an object in JavaScript but if you’re fairly new to JavaScript you might call the items that were storing below an array.

items.set('numbers', [1,2,3,4,5])
items.get('numbers') //output: [1, 2, 3, 4, 5]
items.get('numbers')[2] //output: 3
items.get('numbers')[2] + items.get('numbers')[1] //output: 5

We can also store objects. Yeah I know that I just called arrays as objects a few seconds back so don’t take my word for it as I’m not a JavaScript expert.

var people = {
 name: 'kyokasuigetsu',
 role: 'katana',
 ability: 'illusion'
}

We can simply use the name of the object to store them in the items store.

items.set('obj', people)

You can also get the whole object.

items.get('obj')

You’ll get an object tree if you execute the code above.
image

We can also get the values of individual properties that are stored in the objects.

items.get('obj').role //output: "katana"

Mini Project

Ok enough with the basics this time were gonna be building a mini project using localStorage and Store.js. Here’s what our output is going to look like.

image

Yeah I know it’s a bit ugly but I’m trying to keep the styling simple so it won’t get in the way of our main subject which is localStorage and store.js so just bear with me. Just modify the styling to your liking once were done with it. And here’s the demo in case you want to get a feel of it before we build it.

As you can see from the screenshot above our mini project is going to allow us to create 3 characters with name, skills, and items as its attributes. There is a function that will allow us to reset the storage which means deleting the contents of the localStorage. There is also a function that will allow us to delete a single character from our list. Were also going to implement event listeners which allows us to listen for events in the localStorage, this will allow us to do something on any instance of our project on the same browser window. Basically what we want is to automatically update other tabs which is accessing the same page so that if we delete something on one tab, the other tab will also have that change even if we didn’t perform the delete action from that tab.

First let’s define the styling for our mini project.

<style>
#create, .box {
    width: 210px;
    height: 220px;
    padding: 17px;
	border: 2px solid;
	float:left;
}

#characters{
	width: 744px;
	height: 254px;
	border: 2px solid black;
	float:left;
}
</style>

For this mini project I also used jquery to minimize the code that we need to write. So include it on your page as well.

<script src="store.js"></script>
<script src="jquery171.js></script>

Next is the form where the user is going to create a new character.

<div id="create">
	<h2>Create Character</h2>
	<p>
	<label for="name">Name</label>
	<input type="text" id="name"/>
	</p>

	<p>
	<label for="name">Skills</label>
	<input type="text" id="skills"/>
	</p>

	<p>
	<label for="name">Items</label>
	<input type="text" id="items"/>
	</p>

	<p>
	<input type="button" id="btn_create" value="create"/>
	<input type="button" id="btn_reset" value="reset storage"/>
	</p>
</div>

And then the container where we are going to put our characters later on.

<div id="characters"></div>

Initialize the variable where we are going to store the characters temporarily and permanently (until user decides to delete it)

var chars = []; //store characters temporarily
var s_char = new Store('character'); //store characters until you delete it

Next check if there is already a character that was saved in the character store. If there is already a character (1 or more characters) then we loop through the character store and get the character information (name, skills, items) then display them on the container for characters using the put_contents() function.

The put_contents() function which takes up 4 arguments: the id, name, skills, and the items. The variable x stores the index of the character in the character store so we used it as an id.

if(s_char.get('characters')){
	for(var x in s_char.get('characters')){
	   var name = s_char.get('characters')[x]['name'];
	   var skills = s_char.get('characters')[x]['skills'];
	   var items = s_char.get('characters')[x]['items'];

	   put_contents(x, name, skills, items);
	}
}

The put_contents() function is used to append character information into the character container.

function put_contents(id, name, skills, items){
		var div = $("<div>").attr('class', 'box').appendTo('#characters');
		$("<p>").text('Name: ' + name).appendTo(div);
		$("<p>").text('Skills: ' + skills).appendTo(div);
		$("<p>").text('Items: ' + items).appendTo(div);
		$("<p>").html("<input type='button' class='btn_delete' id="+ id +" value='delete'/>").appendTo(div);
	}

Next we listen for the click even on the create character button.

$('#btn_create').click(function(e){
	var character_count = $('.box').length;
	if(character_count < 3){ //we can only add up to 3 characters
		var name	= $('#name').val();
		var skills	= $('#skills').val();
		skills = skills.split(','); //convert skills to array
		var items	= $('#items').val();
		items = items.split(','); //convert to items array

		//create a template for the character
		var character = function(name, skills, items){
		 this.name = name,
		 this.skills = skills,
		 this.items = items
		}

		//create new characters from the template
		chars[character_count] = new character(name, skills, items);

		s_char.set('characters', chars); //save character to store

		put_contents(character_count, name, skills, items);

		$('input[type=text]').val(''); //clear all textbox
	}else{
		alert('Cannot create more than 3 characters');
	}
});

I really got lazy in writing the code for the deletion of a single character. What I did was to empty the whole container for character, create a copy of the current characters in the storage, delete the character from the copy, copy back the contents of the copy into the store, then finally loop through all the characters stored in the store and display them on the character container.

$('.btn_delete').live('click', function(){

	//using delete leaves an undefined item on the index
	//that was deleted the following code
	//removes the undefined items
	$('.box').remove();
	var characters = s_char.get('characters');
	var id = $(this).attr('id');

	delete characters[id];

	var tmpArray = new Array();
	for(el in characters) {
		 if(characters[el]) { //if current item is not a falsy value
			  tmpArray.push(characters[el]);
		 }
	}
	s_char.set('characters', tmpArray);  //save to store

	//loop through the new list of characters
	for(var x in tmpArray){
		var name = tmpArray[x]['name'];
		var skills = tmpArray[x]['skills'];
		var items = tmpArray[x]['items'];

		put_contents(x, name, skills, items);
	}
});

To clear all the characters we just use the reset method in store.js what it does is to remove all the values from a store and then restore the defaults.

$('#btn_reset').click(function(){
	s_char.reset(); //resets the s_char store
	alert('Storage has been successfully reset!');
	$('.box').remove();
});

Lastly we add an event listener to localStorage so that if something happens to it (adding of items, deletion of items, etc.) an event will be executed on other tabs that accesses the same page on the same window.

The code below is pretty simple, it says that when something happens to the localStorage we reload the page. So if we have three tabs open (1 for the 1 that were currently looking at and 2 for the other tabs which is also navigated to the same page) the other 2 tabs will reload if we add, delete or reset the storage. There are a lot of better ways to do this but for the sake of simplicity and laziness here’s what I did so I advise you not to follow this one if you’re doing this for a client or some serious personal project.

window.addEventListener("storage", function(e){
	location.reload();
}, false);

Conclusion

That’s pretty much all I got for this tutorial. You’ve learned how to do things in localStorage and store.js, we also built a mini project utilizing the power of store.js. I hope you enjoyed this tutorial. Please comment if you think its terrible or there’s some information that is missing so that I could improve it. If you know of alternatives to store.js share them in the comments. Thanks!

Resources