'], ['t2._trackPageview'], ['t2._trackPageLoadTime'] ); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
Skip to content

Recent Articles

17
Sep

Definition of an class method

Definition of an class method
A class method/functions is the behavior/functionality of a class i.e. they provide the necessary code for the class in which it is defined. Examples could be a saveCustomer() method in the class Customer or a printDocument() in the Document class.

Methods act (perform operations) on the data members of the class and can be declared as private or public. A class method is exactly similar to PHP functions, it’s just that class functions are declared inside classes and accessed using the -> (arrow operator / dereferencing operator).

Methods can also be declared as either public, protected or private.

Lets look at an example to understand PHP5 Class methods better:

Example Code:

class Customer {
	private $name;
	public functionsetName($name) {
		$this->name = $name;
	}
}

$c1 = new Customer();
$c1->setName("Sunil Bhatia");

In the above example setName() is the class method of the Customer class. The setName() class method is responsible for accepting the name of the customer and storing it in the internal data member i.e. $name.

The reason why you require methods is so that you can perform necessary validations on the data passed. Let’s re-look at the above example with necessary validation code.

class Customer {
	private $name;
	public function setName($name) {
		if(trim($name) != "") {
			$this->name = $name;
			return true;
		}
		else {
			return false;
		}
	}
}

$c1 = new Customer();
$c1->setName("Sunil Bhatia");

In the above example the setName() method accepts a customer’s name and validates to check if $name is blank. If $name is blank the setName() function returns false; otherwise it stores the $name in the $this->name of the class and returns true.

Notes on Accessor and Mutator methods

Although we will learn about Access Specifiers in the subsequent tutorials; let’s try to understand the meaning and need for accessor and mutator methods.

Accessor Methods:
Accessor methods are also know as getter methods. The reason why we need an accessor method is to be able to read the value of a property/attribute in a class object. In real OOAD practice most of the data members that you define would either be private or protected (more on this will be covered in the tutorial on Access specifiers), therefore to access data of such data members that have been defined as either private or protected will require an implementation of accessor or getter methods.

Note: To make a property or data member as non-read only; you should not provide a getter or accessor method.

Mutator Methods:

Mutator methods are opposite to accessor methods. Mutator methods provides a mechanism to store data in data members that have either been declared as private or protected. The reason why you should provide a mutator method is to provide necessary validation on the data that is to be stored in the data member of the class.

Note: To make a property or data member as read only; you should not provide a setter or mutator method.

Lets look at an example of accessor and mutator methods below:

class Customer {
	private $name;

	//mutator method
	public function setName($name) {
		if(trim($name) != "") {
			$this->name = $name;
			return true;
		}
		else {
			return false;
		}
	}

	//accessor method
	public getName() {
		return $this->name;
	}
}

$c1 = new Customer();
$c1->setName("Sunil Bhatia");
echo $c1->getName();

Output:
Sunil Bhatia

In the above example the setName() method accepts a customer’s name and validates to check if $name is blank. If $name is blank the setName() function returns false; otherwise it stores the $name in the $this->name of the class and returns true. The getName() returns the name stored in the $name data member of the $c1 object.

In the next tutorial you will learn about PHP5 Constructor.

16
Aug

Commonly used Jquery

The explosion of JavaScript libraries and frameworks such as jQuery onto the front-end development scene has opened up the power of JavaScript to a far wider audience than ever before. It was born of the need — expressed by a crescendo of screaming by front-end developers who were fast running out of hair to pull out — to improve JavaScript’s somewhat primitive API, to make up for the lack of unified implementation across browsers and to make it more compact in its syntax.
All of which means that, unless you have some odd grudge against jQuery, those days are gone — you can actually get stuff done now. A script to find all links of a certain CSS class in a document and bind an event to them now requires one line of code, not 10. To power this, jQuery brings to the party its own API, featuring a host of functions, methods and syntactical peculiarities. Some are confused or appear similar to each other but actually differ in some way. This article clears up some of these confusions.
[Offtopic: by the way, did you already get your copy of the Smashing Book?]
1. .parent() vs. .parents() vs. .closest()
All three of these methods are concerned with navigating upwards through the DOM, above the element(s) returned by the selector, and matching certain parents or, beyond them, ancestors. But they differ from each other in ways that make them each uniquely useful.
parent(selector)
This simply matches the one immediate parent of the element(s). It can take a selector, which can be useful for matching the parent only in certain situations. For example:
1
$(‘span#mySpan’).parent().css(‘background’, ‘#f90′);
2
$(‘p’).parent(‘div.large’).css(‘background’, ‘#f90′);
The first line gives the parent of #mySpan. The second does the same for parents of all <p> tags, provided that the parent is a div and has the class large.
Tip: the ability to limit the reach of methods like the one in the second line is a common feature of jQuery. The majority of DOM manipulation methods allow you to specify a selector in this way, so it’s not unique to parent().
parents(selector)
This acts in much the same way as parent(), except that it is not restricted to just one level above the matched element(s). That is, it can return multiple ancestors. So, for example:
1
$(‘li.nav’).parents(‘li’); //for each LI that has the class nav, go find all its parents/ancestors that are also LIs
This says that for each <li> that has the class nav, return all its parents/ancestors that are also <li>s. This could be useful in a multi-level navigation tree, like the following:
01
<ul id=’nav’>
02
<li>Link 1
03
<ul>
04
<li>Sub link 1.1</li>
05
<li>Sub link 1.2</li>
06
<li>Sub link 1.3</li>
07
</ul>
08
<li>Link 2
09
<ul>
10
<li>Sub link 2.1
11
12
<li>Sub link 2.2
13
14
</ul>
15
</li>
16
</ul>
Imagine we wanted to color every third-generation <li> in that tree orange. Simple:
1
$(‘#nav li’).each(function() {
2
if ($(this).parents(‘#nav li’).length == 2)
3
$(this).css(‘color’, ‘#f90′);
4
});
This translates like so: for every <li> found in #nav (hence our each() loop), whether it’s a direct child or not, see how many <li> parents/ancestors are above it within #nav. If the number is two, then this <li> must be on level three, in which case color.
closest(selector)
This is a bit of a well-kept secret, but very useful. It works like parents(), except that it returns only one parent/ancestor. In my experience, you’ll normally want to check for the existence of one particular element in an element’s ancestry, not a whole bunch of them, so I tend to use this more than parent(). Say we wanted to know whether an element was a descendent of another, however deep in the family tree:
1
if ($(‘#element1′).closest(‘#element2′).length == 1)
2
alert(“yes – #element1 is a descendent of #element2!”);
3
else
4
alert(“No – #element1 is not a descendent of #element2″);
Tip: you can simulate closest() by using parents() and limiting it to one returned element.
1
$($(‘#element1′).parents(‘#element2′).get(0)).css(‘background’, ‘#f90′);
One quirk about closest() is that traversal starts from the element(s) matched by the selector, not from its parent. This means that if the selector that passed inside closest() matches the element(s) it is running on, it will return itself. For example:
1
$(‘div#div2′).closest(‘div’).css(‘background’, ‘#f90′);
This will turn #div2 itself orange, because closest() is looking for a <div>, and the nearest <div> to #div2 is itself.
2. .position() vs. .offset()
These two are both concerned with reading the position of an element — namely the first element returned by the selector. They both return an object containing two properties, left and top, but they differ in what the returned position is relative to.
position() calculates positioning relative to the offset parent — or, in more understandable terms, the nearest parent or ancestor of this element that has position: relative. If no such parent or ancestor is found, the position is calculated relative to the document (i.e. the top-left corner of the viewport).
offset(), in contrast, always calculates positioning relative to the document, regardless of the position attribute of the element’s parents and ancestors.
Consider the following two <div>s:
Hello – I’m outerDiv. I have position: relative and left: 100px
Hi – I’m #innerDiv. I have position absolute, left: 50px and top: 80px.
Querying (no pun intended) the offset() and position() of #innerDiv will return different results.
1
var position = $(‘#innerDiv’).position();
2
var offset = $(‘#innerDiv’).offset();
3
alert(“Position: left = “+position.left+”, top = “+position.top+”\n”+
4
“Offset: left = “+offset.left+” and top = “+offset.top
5
)
Try it yourself to see the results: click here.
3. .css(‘width’) and .css(‘height’) vs. .width() and .height()
These three, you won’t be shocked to learn, are concerned with calculating the dimensions of an element in pixels. They both return the offset dimensions, which are the genuine dimensions of the element no matter how stretched it is by its inner content.
They differ in the data types they return: css(‘width’) and css(‘height’) return dimensions as strings, with px appended to the end, while width() and height() return dimensions as integers.
There’s actually another little-known difference that concerns IE (quelle surprise!), and it’s why you should avoid the css(‘width’) and css(‘height’) route. It has to do with the fact that IE, when asked to read “computed” (i.e. not implicitly set) dimensions, unhelpfully returns auto. In jQuery core, width() and height() are based on the .offsetWidth and .offsetHeight properties resident in every element, which IE does read correctly.
But if you’re working on elements with dimensions implicitly set, you don’t need to worry about that. So, if you wanted to read the width of one element and set it on another element, you’d opt for css(‘width’), because setting dimensions, just like in CSS, requires specifying a unit of measurement.
But if you wanted to read an element’s width() with a view to performing a calculation on it, you’d be interested only in the figure; hence width() is better.
Note that each of these can simulate the other with the help of an extra line of JavaScript, like so:
1
var width = $(‘#someElement’).width(); //returns integer
2
width = width+’px’; //now it’s a string like css(‘width’) returns
3
var width = $(‘#someElement’).css(‘width’); //returns string
4
width = parseInt(width); //now it’s an integer like width() returns
Lastly, width() and height() actually have another trick up their sleeves: they can return the dimensions of the window and document. If you try this using the css() method, you’ll get an error.
4. .click() (etc) vs. .bind() vs. .live() vs. .delegate
These are all concerned with binding events to elements. The differences lie in what elements they bind to and how much we can influence the event handler (or “callback”). If this sounds confusing, don’t worry. I’ll explain.
click() (etc)
It’s important to understand that bind() is the daddy of jQuery’s event-handling API. Most tutorials deal with events with simple-looking methods, such as click() and mouseover(), but behind the scenes these are just the lieutenants who report back to bind().
These lieutenants, or aliases, give you quick access to bind certain event types to the elements returned by the selector. They all take one argument: a callback function to be executed when the event fires. For example:
1
$(‘#table td ‘).click(function() {
2
alert(“The TD you clicked contains ‘”+$(this).text()+”‘”);
3
});
This simply says that whenever a <div> inside #table is clicked, alert its text content.
bind()
We can do the same thing with bind, like so:
1
$(‘#table td ‘).bind(‘click’, function() {
2
alert(“The TD you clicked contains ‘”+$(this).text()+”‘”);
3
});
Note that this time, the event type is passed as the first argument to bind(), with the callback as the second argument. Why would you use bind() over the simpler alias functions?
Very often you wouldn’t. But bind() gives you more control over what happens in the event handler. It also allows you to bind more than one event at a time, by space-separating them as the first argument, like so:
1
$(‘#table td’).bind(‘click contextmenu’, function() {
2
alert(“The TD you clicked contains ‘”+$(this).text()+”‘”);
3
});
Now, our event fires whether we’ve clicked the <td> with the left or right button. I also mentioned that bind() gives you more control over the event handler. How does that work? It does it by passing three arguments rather than two, with argument two being a data object containing properties readable to the callback, like so:
1
$(‘#table td’).bind(‘click contextmenu’, {message: ‘hello!’}, function(e) {
2
alert(e.data.message);
3
});
As you can see, we’re passing into our callback a set of variables for it to have access to, in our case the variable message.
You might wonder why we would do this. Why not just specify any variables we want outside the callback and have our callback read those? The answer has to do with scope and closures. When asked to read a variable, JavaScript starts in the immediate scope and works outwards (this is a fundamentally different behavior to languages such as PHP). Consider the following:
1
var message = ‘you left clicked a TD’;
2
$(‘#table td’).bind(‘click’, function(e) {
3
alert(message);
4
});
5
var message = ‘you right clicked a TD’;
6
$(‘#table td’).bind(‘contextmenu’, function(e) {
7
alert(message);
8
});
No matter whether we click the <td> with the left or right mouse button, we will be told it was the right one. This is because the variable message is read by the alert() at the time of the event firing, not at the time the event was bound.
If we give each event its own “version” of message at the time of binding the events, we solve this problem.
1
$(‘#table td’).bind(‘click’, {message: ‘You left clicked a TD’}, function(e) {
2
alert(e.data.message);
3
});
4
$(‘#table td’).bind(‘contextmenu’, {message: ‘You right clicked a TD’}, function(e) {
5
alert(e.data.message);
6
});
Events bound with bind() and with the alias methods (.mouseover(), etc) are unbound with the unbind() method.
live()
This works almost exactly the same as bind() but with one crucial difference: events are bound both to current and future elements — that is, any elements that do not currently exist but which may be DOM-scripted after the document is loaded.
Side note: DOM-scripting entails creating and manipulating elements in JavaScript. Ever notice in your Facebook profile that when you “add another employer” a field magically appears? That’s DOM-scripting, and while I won’t get into it here, it looks broadly like this:
1
var newDiv = document.createElement(‘div’);
2
newDiv.appendChild(document.createTextNode(‘hello, world!’));
3
$(newDiv).css({width: 100, height: 100, background: ‘#f90′});
4
document.body.appendChild(newDiv);
delegate()
Another shortfall of live() is that, unlike the vast majority of jQuery methods, it cannot be used in chaining. That is, it must be used directly on a selector, like so:
1
$(‘#myDiv a’).live(‘mouseover’, function() {
2
alert(‘hello’);
3
});
But not…
1
$(‘#myDiv’).children(‘a’).live(‘mouseover’, function() {
2
alert(‘hello’);
3
});
… which will fail, as it will if you pass direct DOM elements, such as $(document.body).
delegate(), which was developed as part of jQuery 1.4.2, goes some way to solving this problem by accepting as its first argument a context within the selector. For example:
1
$(‘#myDiv’).delegate(‘a’, ‘mouseover’, function() {
2
alert(‘hello’);
3
});
Like live(), delegate() binds events both to current and future elements. Handlers are unbound via the undelegate() method.
Real-Life Example
For a real-life example, I want to stick with DOM-scripting, because this is an important part of any RIA (rich Internet application) built in JavaScript.
Let’s imagine a flight-booking application. The user is asked to supply the names of all passengers travelling. Entered passengers appear as new rows in a table, #passengersTable, with two columns: “Name” (containing a text field for the passenger) and “Delete” (containing a button to remove the passenger’s row).
To add a new passenger (i.e. row), the user clicks a button, #addPassenger:
01
$(‘#addPassenger’).click(function() {
02
var tr = document.createElement(‘tr’);
03
var td1 = document.createElement(‘td’);
04
var input = document.createElement(‘input’);
05
input.type = ‘text’;
06
$(td1).append(input);
07
var td2 = document.createElement(‘td’);
08
var button = document.createElement(‘button’);
09
button.type = ‘button’;
10
$(button).text(‘delete’);
11
$(td2).append(button);
12
$(tr).append(td1);
13
$(tr).append(td2);
14
$(‘#passengersTable tbody’).append(tr);
15
});
Notice that the event is applied to #addPassenger with click(), not live(‘click’), because we know this button will exist from the beginning.
What about the event code for the “Delete” buttons to delete a passenger?
1
$(‘#passengersTable td button’).live(‘click’, function() {
2
if (confirm(“Are you sure you want to delete this passenger?”))
3
$(this).closest(‘tr’).remove();
4
});
Here, we apply the event with live() because the element to which it is being bound (i.e. the button) did not exist at runtime; it was DOM-scripted later in the code to add a passenger.
Handlers bound with live() are unbound with the die() method.
The convenience of live() comes at a price: one of its drawbacks is that you cannot pass an object of multiple event handlers to it. Only one handler.
5. .children() vs. .find()
Remember how the differences between parent(), parents() and closest() really boiled down to a question of reach? So it is here.
children()
This returns the immediate children of an element or elements returned by a selector. As with most jQuery DOM-traversal methods, it is optionally filtered with a selector. So, if we wanted to turn all <td>s in a table that contained the word “dog” orange, we could use this:
1
$(‘#table tr’).children(‘td:contains(dog)’).css(‘background’, ‘#f90′);
find()
This works very similar to children(), only it looks at both children and more distant descendants. It is also often a safer bet than children().
Say it’s your last day on a project. You need to write some code to hide all <tr>s that have the class hideMe. But some developers omit <tbody> from their table mark-up, so we need to cover all bases for the future. It would be risky to target the <tr>s like this…
1
$(‘#table tbody tr.hideMe’).hide();
… because that would fail if there’s no <tbody>. Instead, we use find():
1
$(‘#table’).find(‘tr.hideMe’).hide();
This says that wherever you find a <tr> in #table with .hideMe, of whatever descendancy, hide it.
6. .not() vs. !.is() vs. :not()
As you’d expect from functions named “not” and “is,” these are opposites. But there’s more to it than that, and these two are not really equivalents.
.not()
not() returns elements that do not match its selector. For example:
1
$(‘p’).not(‘.someclass’).css(‘color’, ‘#f90′);
That turns all paragraphs that do not have the class someclass orange.
.is()
If, on the other hand, you want to target paragraphs that do have the class someclass, you could be forgiven for thinking that this would do it:
1
$(‘p’).is(‘.someclass’).css(‘color’, ‘#f90′);
In fact, this would cause an error, because is() does not return elements: it returns a boolean. It’s a testing function to see whether any of the chain elements match the selector.
So when is is useful? Well, it’s useful for querying elements about their properties. See the real-life example below.
:not()
:not() is the pseudo-selector equivalent of the method .not() It performs the same job; the only difference, as with all pseudo-selectors, is that you can use it in the middle of a selector string, and jQuery’s string parser will pick it up and act on it. The following example is equivalent to our .not() example above:
1
$(‘p:not(.someclass)’).css(‘color’, ‘#f90′);
Real-Life Example
As we’ve seen, .is() is used to test, not filter, elements. Imagine we had the following sign-up form. Required fields have the class required.
01
<form id=’myform’ method=’post’ action=’somewhere.htm’>
02
<label>Forename *
03
<input type=’text’ class=’required’ />
04
<br />
05
<label>Surname *
06
<input type=’text’ class=’required’ />
07
<br />
08
<label>Phone number
09
<input type=’text’ />
10
<br />
11
<label>Desired username *
12
<input type=’text’ class=’required’ />
13
<br />
14
<input type=’submit’ value=’GO’ />
15
</form>
When submitted, our script should check that no required fields were left blank. If they were, the user should be notified and the submission halted.
1
$(‘#myform’).submit(function() {
2
if ($(this).find(‘input’).is(‘.required[value=]‘)) {
3
alert(‘Required fields were left blank! Please correct.’);
4
return false; //cancel submit event
5
}
6
});
Here we’re not interested in returning elements to manipulate them, but rather just in querying their existence. Our is() part of the chain merely checks for the existence of fields within #myform that match its selector. It returns true if it finds any, which means required fields were left blank.
7. .filter() vs. .each()
These two are concerned with iteratively visiting each element returned by a selector and doing something to it.
.each()
each() loops over the elements, but it can be used in two ways. The first and most common involves passing a callback function as its only argument, which is also used to act on each element in succession. For example:
1
$(‘p’).each(function() {
2
alert($(this).text());
3
});
This visits every <p> in our document and alerts out its contents.
But each() is more than just a method for running on selectors: it can also be used to handle arrays and array-like objects. If you know PHP, think foreach(). It can do this either as a method or as a core function of jQuery. For example…
1
var myarray = ['one', 'two'];
2
$.each(myarray, function(key, val) {
3
alert(‘The value at key ‘+key+’ is ‘+val);
4
});
… is the same as:
1
var myarray = ['one', 'two'];
2
$(myarray).each(function(key, val) {
3
alert(‘The value at key ‘+key+’ is ‘+val);
4
});
That is, for each element in myarray, in our callback function its key and value will be available to read via the key and val variables, respectively.
One of the great things about this is that you can also iterate over objects — but only in the first way (i.e. $.each).
jQuery is known as a DOM-manipulation and effects framework, quite different in focus from other frameworks such as MooTools, but each() is an example of its occasional foray into extending JavaScript’s native API.
.filter()
filter(), like each(), visits each element in the chain, but this time to remove it from the chain if it doesn’t pass a certain test.
The most common application of filter() is to pass it a selector string, just like you would specify at the start of a chain. So, the following are equivalents:
1
$(‘p.someClass’).css(‘color’, ‘#f90′);
2
$(‘p’).filter(‘.someclass’).css(‘color’, ‘#f90′);
In which case, why would you use the second example? The answer is, sometimes you want to affect element sets that you cannot (or don’t want to) change. For example:
1
var elements = $(‘#someElement div ul li a’);
2
//hundreds of lines later…
3
elements.filter(‘.someclass’).css(‘color’, ‘#f90′);
elements was set long ago, so we cannot — indeed may not wish to — change the elements that return, but we might later want to filter them.
filter() really comes into its own, though, when you pass it a filter function to which each element in the chain in turn is passed. Whether the function returns true or false determines whether the element stays in the chain. For example:
1
$(‘p’).filter(function() {
2
return $(this).text().indexOf(‘hello’) != -1;
3
}).css(‘color’, ‘#f90′)
Here, for each <p> found in the document, if it contains the string hello, turn it orange. Otherwise, don’t affect it.
We saw above how is(), despite its name, was not the equivalent of not(), as you might expect. Rather, use filter() as the positive equivalent of not().
Note also that unlike each(), filter() cannot be used on arrays and objects.
Real-Life Example
You might be looking at the example above, where we turned <p>s starting with hello orange, and thinking, “But we could do that more simply.” You’d be right:
1
$(‘p:contains(hello)’).css(‘color’, ‘#f90′)
For such a simple condition (i.e. contains hello), that’s fine. But filter() is all about letting us perform more complex or long-winded evaluations before deciding whether an element can stay in our chain.
Imagine we had a table of CD products with four columns: artist, title, genre and price. Using some controls at the top of the page, the user stipulates that they do not want to see products for which the genre is “Country” or the price is above $10. These are two filter conditions, so we need a filter function:
1
$(‘#productsTable tbody tr’).filter(function() {
2
var genre = $(this).children(‘td:nth-child(3)’).text();
3
var price = $(this).children(‘td:last’).text().replace(/[^\d\.]+/g, ”);
4
return genre.toLowerCase() == ‘country’ || parseInt(price) >= 10;
5
}).hide();
So, for each <tr> inside the table, we evaluate columns 3 and 4 (genre and price), respectively. We know the table has four columns, so we can target column 4 with the :last pseudo-selector. For each product looked at, we assign the genre and price to their own variables, just to keep things tidy.
For the price, we replace any characters that might prevent us from using the value for mathematical calculation. If the column contained the value $14.99 and we tried to compute that by seeing whether it matched our condition of being below $10, we would be told that it’s not a number, because it contains the $ sign. Hence we strip away everything that is not number or dot.
Lastly, we return true (meaning the row will be hidden) if either of our conditions are met (i.e. the genre is country or the price is $10 or more).
filter()
8. .merge() vs. .extend()
Let’s finish with a foray into more advanced JavaScript and jQuery. We’ve looked at positioning, DOM manipulation and other common issues, but jQuery also provides some utilities for dealing with the native parts of JavaScript. This is not its main focus, mind you; libraries such as MooTools exist for this purpose.
.merge()
merge() allows you to merge the contents of two arrays into the first array. This entails permanent change for the first array. It does not make a new array; values from the second array are appended to the first:
1
var arr1 = ['one', 'two'];
2
var arr2 = ['three', 'four'];
3
$.merge(arr1, arr2);
After this code runs, the arr1 will contain four elements, namely one, two, three, four. arr2 is unchanged. (If you’re familiar with PHP, this function is equivalent to array_merge().)
.extend()
extend() does a similar thing, but for objects:
1
var obj1 = {one: ‘un’, two: ‘deux’}
2
var obj2 = {three: ‘trois’, four: ‘quatre’}
3
$.extend(obj1, obj2);
extend() has a little more power to it. For one thing, you can merge more than two objects — you can pass as many as you like. For another, it can merge recursively. That is, if properties of objects are themselves objects, you can ensure that they are merged, too. To do this, pass true as the first argument:
1
var obj1 = {one: ‘un’, two: ‘deux’}
2
var obj2 = {three: ‘trois’, four: ‘quatre’}
3
$.extend(true, obj1, obj2);
Covering everything about the behaviour of JavaScript objects (and how merge interacts with them) is beyond the scope of this article, but you can read more here.
The difference between merge() and extend() in jQuery is not the same as it is in MooTools. One is used to amend an existing object, the other creates a new copy.

The explosion of JavaScript libraries and frameworks such as jQuery onto the front-end development scene has opened up the power of JavaScript to a far wider audience than ever before. It was born of the need — expressed by a crescendo of screaming by front-end developers who were fast running out of hair to pull out — to improve JavaScript’s somewhat primitive API, to make up for the lack of unified implementation across browsers and to make it more compact in its syntax.
All of which means that, unless you have some odd grudge against jQuery, those days are gone — you can actually get stuff done now. A script to find all links of a certain CSS class in a document and bind an event to them now requires one line of code, not 10. To power this, jQuery brings to the party its own API, featuring a host of functions, methods and syntactical peculiarities. Some are confused or appear similar to each other but actually differ in some way. This article clears up some of these confusions.
[Offtopic: by the way, did you already get your copy of the Smashing Book?]
1. .parent() vs. .parents() vs. .closest()
All three of these methods are concerned with navigating upwards through the DOM, above the element(s) returned by the selector, and matching certain parents or, beyond them, ancestors. But they differ from each other in ways that make them each uniquely useful.
parent(selector)
This simply matches the one immediate parent of the element(s). It can take a selector, which can be useful for matching the parent only in certain situations. For example:
1$(‘span#mySpan’).parent().css(‘background’, ‘#f90′);2$(‘p’).parent(‘div.large’).css(‘background’, ‘#f90′);The first line gives the parent of #mySpan. The second does the same for parents of all <p> tags, provided that the parent is a div and has the class large.
Tip: the ability to limit the reach of methods like the one in the second line is a common feature of jQuery. The majority of DOM manipulation methods allow you to specify a selector in this way, so it’s not unique to parent().
parents(selector)
This acts in much the same way as parent(), except that it is not restricted to just one level above the matched element(s). That is, it can return multiple ancestors. So, for example:
1$(‘li.nav’).parents(‘li’); //for each LI that has the class nav, go find all its parents/ancestors that are also LIsThis says that for each <li> that has the class nav, return all its parents/ancestors that are also <li>s. This could be useful in a multi-level navigation tree, like the following:
01<ul id=’nav’>02    <li>Link 103        <ul>04            <li>Sub link 1.1</li>05            <li>Sub link 1.2</li>06            <li>Sub link 1.3</li>07        </ul>08    <li>Link 209        <ul>10            <li>Sub link 2.111 12            <li>Sub link 2.213 14        </ul>15    </li>16</ul>Imagine we wanted to color every third-generation <li> in that tree orange. Simple:
1$(‘#nav li’).each(function() {2    if ($(this).parents(‘#nav li’).length == 2)3        $(this).css(‘color’, ‘#f90′);4});This translates like so: for every <li> found in #nav (hence our each() loop), whether it’s a direct child or not, see how many <li> parents/ancestors are above it within #nav. If the number is two, then this <li> must be on level three, in which case color.
closest(selector)
This is a bit of a well-kept secret, but very useful. It works like parents(), except that it returns only one parent/ancestor. In my experience, you’ll normally want to check for the existence of one particular element in an element’s ancestry, not a whole bunch of them, so I tend to use this more than parent(). Say we wanted to know whether an element was a descendent of another, however deep in the family tree:
1if ($(‘#element1′).closest(‘#element2′).length == 1)2    alert(“yes – #element1 is a descendent of #element2!”);3else4    alert(“No – #element1 is not a descendent of #element2″);Tip: you can simulate closest() by using parents() and limiting it to one returned element.
1$($(‘#element1′).parents(‘#element2′).get(0)).css(‘background’, ‘#f90′);One quirk about closest() is that traversal starts from the element(s) matched by the selector, not from its parent. This means that if the selector that passed inside closest() matches the element(s) it is running on, it will return itself. For example:
1$(‘div#div2′).closest(‘div’).css(‘background’, ‘#f90′);This will turn #div2 itself orange, because closest() is looking for a <div>, and the nearest <div> to #div2 is itself.
2. .position() vs. .offset()
These two are both concerned with reading the position of an element — namely the first element returned by the selector. They both return an object containing two properties, left and top, but they differ in what the returned position is relative to.
position() calculates positioning relative to the offset parent — or, in more understandable terms, the nearest parent or ancestor of this element that has position: relative. If no such parent or ancestor is found, the position is calculated relative to the document (i.e. the top-left corner of the viewport).
offset(), in contrast, always calculates positioning relative to the document, regardless of the position attribute of the element’s parents and ancestors.
Consider the following two <div>s:
Hello – I’m outerDiv. I have position: relative and left: 100px
Hi – I’m #innerDiv. I have position absolute, left: 50px and top: 80px.
Querying (no pun intended) the offset() and position() of #innerDiv will return different results.
1var position = $(‘#innerDiv’).position();2var offset = $(‘#innerDiv’).offset();3alert(“Position: left = “+position.left+”, top = “+position.top+”\n”+4      ”Offset: left = “+offset.left+” and top = “+offset.top5)Try it yourself to see the results: click here.
3. .css(‘width’) and .css(‘height’) vs. .width() and .height()
These three, you won’t be shocked to learn, are concerned with calculating the dimensions of an element in pixels. They both return the offset dimensions, which are the genuine dimensions of the element no matter how stretched it is by its inner content.
They differ in the data types they return: css(‘width’) and css(‘height’) return dimensions as strings, with px appended to the end, while width() and height() return dimensions as integers.
There’s actually another little-known difference that concerns IE (quelle surprise!), and it’s why you should avoid the css(‘width’) and css(‘height’) route. It has to do with the fact that IE, when asked to read “computed” (i.e. not implicitly set) dimensions, unhelpfully returns auto. In jQuery core, width() and height() are based on the .offsetWidth and .offsetHeight properties resident in every element, which IE does read correctly.
But if you’re working on elements with dimensions implicitly set, you don’t need to worry about that. So, if you wanted to read the width of one element and set it on another element, you’d opt for css(‘width’), because setting dimensions, just like in CSS, requires specifying a unit of measurement.
But if you wanted to read an element’s width() with a view to performing a calculation on it, you’d be interested only in the figure; hence width() is better.
Note that each of these can simulate the other with the help of an extra line of JavaScript, like so:
1var width = $(‘#someElement’).width(); //returns integer2width = width+’px’; //now it’s a string like css(‘width’) returns3var width = $(‘#someElement’).css(‘width’); //returns string4width = parseInt(width); //now it’s an integer like width() returnsLastly, width() and height() actually have another trick up their sleeves: they can return the dimensions of the window and document. If you try this using the css() method, you’ll get an error.
4. .click() (etc) vs. .bind() vs. .live() vs. .delegate
These are all concerned with binding events to elements. The differences lie in what elements they bind to and how much we can influence the event handler (or “callback”). If this sounds confusing, don’t worry. I’ll explain.
click() (etc)
It’s important to understand that bind() is the daddy of jQuery’s event-handling API. Most tutorials deal with events with simple-looking methods, such as click() and mouseover(), but behind the scenes these are just the lieutenants who report back to bind().
These lieutenants, or aliases, give you quick access to bind certain event types to the elements returned by the selector. They all take one argument: a callback function to be executed when the event fires. For example:
1$(‘#table td ‘).click(function() {2    alert(“The TD you clicked contains ‘”+$(this).text()+”‘”);3});This simply says that whenever a <div> inside #table is clicked, alert its text content.
bind()
We can do the same thing with bind, like so:
1$(‘#table td ‘).bind(‘click’, function() {2    alert(“The TD you clicked contains ‘”+$(this).text()+”‘”);3});Note that this time, the event type is passed as the first argument to bind(), with the callback as the second argument. Why would you use bind() over the simpler alias functions?
Very often you wouldn’t. But bind() gives you more control over what happens in the event handler. It also allows you to bind more than one event at a time, by space-separating them as the first argument, like so:
1$(‘#table td’).bind(‘click contextmenu’, function() {2    alert(“The TD you clicked contains ‘”+$(this).text()+”‘”);3});Now, our event fires whether we’ve clicked the <td> with the left or right button. I also mentioned that bind() gives you more control over the event handler. How does that work? It does it by passing three arguments rather than two, with argument two being a data object containing properties readable to the callback, like so:
1$(‘#table td’).bind(‘click contextmenu’, {message: ‘hello!’}, function(e) {2    alert(e.data.message);3});As you can see, we’re passing into our callback a set of variables for it to have access to, in our case the variable message.
You might wonder why we would do this. Why not just specify any variables we want outside the callback and have our callback read those? The answer has to do with scope and closures. When asked to read a variable, JavaScript starts in the immediate scope and works outwards (this is a fundamentally different behavior to languages such as PHP). Consider the following:
1var message = ‘you left clicked a TD’;2$(‘#table td’).bind(‘click’, function(e) {3    alert(message);4});5var message = ‘you right clicked a TD’;6$(‘#table td’).bind(‘contextmenu’, function(e) {7    alert(message);8});No matter whether we click the <td> with the left or right mouse button, we will be told it was the right one. This is because the variable message is read by the alert() at the time of the event firing, not at the time the event was bound.
If we give each event its own “version” of message at the time of binding the events, we solve this problem.
1$(‘#table td’).bind(‘click’, {message: ‘You left clicked a TD’}, function(e) {2    alert(e.data.message);3});4$(‘#table td’).bind(‘contextmenu’, {message: ‘You right clicked a TD’}, function(e) {5    alert(e.data.message);6});Events bound with bind() and with the alias methods (.mouseover(), etc) are unbound with the unbind() method.
live()
This works almost exactly the same as bind() but with one crucial difference: events are bound both to current and future elements — that is, any elements that do not currently exist but which may be DOM-scripted after the document is loaded.
Side note: DOM-scripting entails creating and manipulating elements in JavaScript. Ever notice in your Facebook profile that when you “add another employer” a field magically appears? That’s DOM-scripting, and while I won’t get into it here, it looks broadly like this:
1var newDiv = document.createElement(‘div’);2newDiv.appendChild(document.createTextNode(‘hello, world!’));3$(newDiv).css({width: 100, height: 100, background: ‘#f90′});4document.body.appendChild(newDiv);delegate()
Another shortfall of live() is that, unlike the vast majority of jQuery methods, it cannot be used in chaining. That is, it must be used directly on a selector, like so:
1$(‘#myDiv a’).live(‘mouseover’, function() {2    alert(‘hello’);3});But not…
1$(‘#myDiv’).children(‘a’).live(‘mouseover’, function() {2    alert(‘hello’);3});… which will fail, as it will if you pass direct DOM elements, such as $(document.body).
delegate(), which was developed as part of jQuery 1.4.2, goes some way to solving this problem by accepting as its first argument a context within the selector. For example:
1$(‘#myDiv’).delegate(‘a’, ‘mouseover’, function() {2    alert(‘hello’);3});Like live(), delegate() binds events both to current and future elements. Handlers are unbound via the undelegate() method.
Real-Life Example
For a real-life example, I want to stick with DOM-scripting, because this is an important part of any RIA (rich Internet application) built in JavaScript.
Let’s imagine a flight-booking application. The user is asked to supply the names of all passengers travelling. Entered passengers appear as new rows in a table, #passengersTable, with two columns: “Name” (containing a text field for the passenger) and “Delete” (containing a button to remove the passenger’s row).
To add a new passenger (i.e. row), the user clicks a button, #addPassenger:
01$(‘#addPassenger’).click(function() {02    var tr = document.createElement(‘tr’);03    var td1 = document.createElement(‘td’);04    var input = document.createElement(‘input’);05    input.type = ‘text’;06    $(td1).append(input);07    var td2 = document.createElement(‘td’);08    var button = document.createElement(‘button’);09    button.type = ‘button’;10    $(button).text(‘delete’);11    $(td2).append(button);12    $(tr).append(td1);13    $(tr).append(td2);14    $(‘#passengersTable tbody’).append(tr);15});Notice that the event is applied to #addPassenger with click(), not live(‘click’), because we know this button will exist from the beginning.
What about the event code for the “Delete” buttons to delete a passenger?
1$(‘#passengersTable td button’).live(‘click’, function() {2    if (confirm(“Are you sure you want to delete this passenger?”))3    $(this).closest(‘tr’).remove();4});Here, we apply the event with live() because the element to which it is being bound (i.e. the button) did not exist at runtime; it was DOM-scripted later in the code to add a passenger.
Handlers bound with live() are unbound with the die() method.
The convenience of live() comes at a price: one of its drawbacks is that you cannot pass an object of multiple event handlers to it. Only one handler.
5. .children() vs. .find()
Remember how the differences between parent(), parents() and closest() really boiled down to a question of reach? So it is here.
children()
This returns the immediate children of an element or elements returned by a selector. As with most jQuery DOM-traversal methods, it is optionally filtered with a selector. So, if we wanted to turn all <td>s in a table that contained the word “dog” orange, we could use this:
1$(‘#table tr’).children(‘td:contains(dog)’).css(‘background’, ‘#f90′);find()
This works very similar to children(), only it looks at both children and more distant descendants. It is also often a safer bet than children().
Say it’s your last day on a project. You need to write some code to hide all <tr>s that have the class hideMe. But some developers omit <tbody> from their table mark-up, so we need to cover all bases for the future. It would be risky to target the <tr>s like this…
1$(‘#table tbody tr.hideMe’).hide();… because that would fail if there’s no <tbody>. Instead, we use find():
1$(‘#table’).find(‘tr.hideMe’).hide();This says that wherever you find a <tr> in #table with .hideMe, of whatever descendancy, hide it.
6. .not() vs. !.is() vs. :not()
As you’d expect from functions named “not” and “is,” these are opposites. But there’s more to it than that, and these two are not really equivalents.
.not()
not() returns elements that do not match its selector. For example:
1$(‘p’).not(‘.someclass’).css(‘color’, ‘#f90′);That turns all paragraphs that do not have the class someclass orange.
.is()
If, on the other hand, you want to target paragraphs that do have the class someclass, you could be forgiven for thinking that this would do it:
1$(‘p’).is(‘.someclass’).css(‘color’, ‘#f90′);In fact, this would cause an error, because is() does not return elements: it returns a boolean. It’s a testing function to see whether any of the chain elements match the selector.
So when is is useful? Well, it’s useful for querying elements about their properties. See the real-life example below.
:not()
:not() is the pseudo-selector equivalent of the method .not() It performs the same job; the only difference, as with all pseudo-selectors, is that you can use it in the middle of a selector string, and jQuery’s string parser will pick it up and act on it. The following example is equivalent to our .not() example above:
1$(‘p:not(.someclass)’).css(‘color’, ‘#f90′);Real-Life Example
As we’ve seen, .is() is used to test, not filter, elements. Imagine we had the following sign-up form. Required fields have the class required.
01<form id=’myform’ method=’post’ action=’somewhere.htm’>02    <label>Forename *03    <input type=’text’ class=’required’ />04    <br />05    <label>Surname *06    <input type=’text’ class=’required’ />07    <br />08    <label>Phone number09    <input type=’text’ />10    <br />11    <label>Desired username *12    <input type=’text’ class=’required’ />13    <br />14    <input type=’submit’ value=’GO’ />15</form>When submitted, our script should check that no required fields were left blank. If they were, the user should be notified and the submission halted.
1$(‘#myform’).submit(function() {2    if ($(this).find(‘input’).is(‘.required[value=]‘)) {3        alert(‘Required fields were left blank! Please correct.’);4        return false; //cancel submit event5    }6});Here we’re not interested in returning elements to manipulate them, but rather just in querying their existence. Our is() part of the chain merely checks for the existence of fields within #myform that match its selector. It returns true if it finds any, which means required fields were left blank.
7. .filter() vs. .each()
These two are concerned with iteratively visiting each element returned by a selector and doing something to it.
.each()
each() loops over the elements, but it can be used in two ways. The first and most common involves passing a callback function as its only argument, which is also used to act on each element in succession. For example:
1$(‘p’).each(function() {2    alert($(this).text());3});This visits every <p> in our document and alerts out its contents.
But each() is more than just a method for running on selectors: it can also be used to handle arrays and array-like objects. If you know PHP, think foreach(). It can do this either as a method or as a core function of jQuery. For example…
1var myarray = ['one', 'two'];2$.each(myarray, function(key, val) {3    alert(‘The value at key ‘+key+’ is ‘+val);4});… is the same as:
1var myarray = ['one', 'two'];2$(myarray).each(function(key, val) {3    alert(‘The value at key ‘+key+’ is ‘+val);4});That is, for each element in myarray, in our callback function its key and value will be available to read via the key and val variables, respectively.
One of the great things about this is that you can also iterate over objects — but only in the first way (i.e. $.each).
jQuery is known as a DOM-manipulation and effects framework, quite different in focus from other frameworks such as MooTools, but each() is an example of its occasional foray into extending JavaScript’s native API.
.filter()
filter(), like each(), visits each element in the chain, but this time to remove it from the chain if it doesn’t pass a certain test.
The most common application of filter() is to pass it a selector string, just like you would specify at the start of a chain. So, the following are equivalents:
1$(‘p.someClass’).css(‘color’, ‘#f90′);2$(‘p’).filter(‘.someclass’).css(‘color’, ‘#f90′);In which case, why would you use the second example? The answer is, sometimes you want to affect element sets that you cannot (or don’t want to) change. For example:
1var elements = $(‘#someElement div ul li a’);2//hundreds of lines later…3elements.filter(‘.someclass’).css(‘color’, ‘#f90′);elements was set long ago, so we cannot — indeed may not wish to — change the elements that return, but we might later want to filter them.
filter() really comes into its own, though, when you pass it a filter function to which each element in the chain in turn is passed. Whether the function returns true or false determines whether the element stays in the chain. For example:
1$(‘p’).filter(function() {2    return $(this).text().indexOf(‘hello’) != -1;3}).css(‘color’, ‘#f90′)Here, for each <p> found in the document, if it contains the string hello, turn it orange. Otherwise, don’t affect it.
We saw above how is(), despite its name, was not the equivalent of not(), as you might expect. Rather, use filter() as the positive equivalent of not().
Note also that unlike each(), filter() cannot be used on arrays and objects.
Real-Life Example
You might be looking at the example above, where we turned <p>s starting with hello orange, and thinking, “But we could do that more simply.” You’d be right:
1$(‘p:contains(hello)’).css(‘color’, ‘#f90′)For such a simple condition (i.e. contains hello), that’s fine. But filter() is all about letting us perform more complex or long-winded evaluations before deciding whether an element can stay in our chain.
Imagine we had a table of CD products with four columns: artist, title, genre and price. Using some controls at the top of the page, the user stipulates that they do not want to see products for which the genre is “Country” or the price is above $10. These are two filter conditions, so we need a filter function:
1$(‘#productsTable tbody tr’).filter(function() {2    var genre = $(this).children(‘td:nth-child(3)’).text();3    var price = $(this).children(‘td:last’).text().replace(/[^\d\.]+/g, ”);4    return genre.toLowerCase() == ‘country’ || parseInt(price) >= 10;5}).hide();So, for each <tr> inside the table, we evaluate columns 3 and 4 (genre and price), respectively. We know the table has four columns, so we can target column 4 with the :last pseudo-selector. For each product looked at, we assign the genre and price to their own variables, just to keep things tidy.
For the price, we replace any characters that might prevent us from using the value for mathematical calculation. If the column contained the value $14.99 and we tried to compute that by seeing whether it matched our condition of being below $10, we would be told that it’s not a number, because it contains the $ sign. Hence we strip away everything that is not number or dot.
Lastly, we return true (meaning the row will be hidden) if either of our conditions are met (i.e. the genre is country or the price is $10 or more).
filter()
8. .merge() vs. .extend()
Let’s finish with a foray into more advanced JavaScript and jQuery. We’ve looked at positioning, DOM manipulation and other common issues, but jQuery also provides some utilities for dealing with the native parts of JavaScript. This is not its main focus, mind you; libraries such as MooTools exist for this purpose.
.merge()
merge() allows you to merge the contents of two arrays into the first array. This entails permanent change for the first array. It does not make a new array; values from the second array are appended to the first:
1var arr1 = ['one', 'two'];2var arr2 = ['three', 'four'];3$.merge(arr1, arr2);After this code runs, the arr1 will contain four elements, namely one, two, three, four. arr2 is unchanged. (If you’re familiar with PHP, this function is equivalent to array_merge().)
.extend()
extend() does a similar thing, but for objects:
1var obj1 = {one: ‘un’, two: ‘deux’}2var obj2 = {three: ‘trois’, four: ‘quatre’}3$.extend(obj1, obj2);extend() has a little more power to it. For one thing, you can merge more than two objects — you can pass as many as you like. For another, it can merge recursively. That is, if properties of objects are themselves objects, you can ensure that they are merged, too. To do this, pass true as the first argument:
1var obj1 = {one: ‘un’, two: ‘deux’}2var obj2 = {three: ‘trois’, four: ‘quatre’}3$.extend(true, obj1, obj2);Covering everything about the behaviour of JavaScript objects (and how merge interacts with them) is beyond the scope of this article, but you can read more here.
The difference between merge() and extend() in jQuery is not the same as it is in MooTools. One is used to amend an existing object, the other creates a new copy.

16
Aug

21 Essentials SEO tips

Small businesses are growing more aware of the need to understand and implement at least the basics of SEO, search engine optimization. But if you read a variety of small businesses blogs and Web sites, you’ll quickly see that there’s a lot of uncertainty over what makes up “the basics.” Without access to high-level consulting and without a lot of experience knowing what SEO resources can be trusted, there’s also a lot of misinformation about SEO strategies and tactics.

Small Business SEO Checklist: The Do’s

1. Commit yourself to the process. SEO isn’t a one-time event. Search engine algorithms change regularly, so the tactics that worked last year may not work this year. SEO requires a long-term outlook and commitment.

2. Be patient. SEO isn’t about instant gratification. Results often take months to see, and this is especially true the smaller you are, and the newer you are to doing business online.

3. Ask a lot of questions when hiring an SEO company. It’s your job to know what kind of tactics the company uses. Ask for specifics. Ask if there are any risks involved. Then get online yourself and do your own research—about the company, about the tactics they discussed, and so forth.

4. Become a student of SEO. If you’re taking the do-it-yourself route, you’ll have to become a student of SEO and learn as much as you can. Luckily for you, there are plenty of great Web resources (like Search Engine Land) and several terrific books you can read. Aaron Wall’s SEO Book, Jennifer Laycock’s Small Business Guide to Search Engine Marketing, and Search Engine Optimization: An Hour a Day by Jennifer Grappone and Gradiva Couzin are three I’ve read and recommend.

5. Have web analytics in place at the start. You should have clearly defined goals for your SEO efforts, and you’ll need web analytics software in place so you can track what’s working and what’s not.

6. Build a great web site. I’m sure you want to show up on the first page of results. Ask yourself, “Is my site really one of the 10 best sites in the world on this topic?” Be honest. If it’s not, make it better.

7. Include a site map page. Spiders can’t index pages that can’t be crawled. A site map will help spiders find all the important pages on your site, and help the spider understand your site’s hierarchy. This is especially helpful if your site has a hard-to-crawl navigation menu. If your site is large, make several site map pages. Keep each one to less than 100 links. I tell clients 75 is the max to be safe.

8. Make SEO-friendly URLs. Use keywords in your URLs and file names, such asyourdomain.com/red-widgets.html. Don’t overdo it, though. A file with 3+ hyphens tends to look spammy and users may be hesitant to click on it. Related bonus tip: Use hyphens in URLs and file names, not underscores. Hyphens are treated as a “space,” while underscores are not.

9. Do keyword research at the start of the project. If you’re on a tight budget, use the free versions of Keyword Discovery or WordTracker, both of which also have more powerful paid versions. Ignore the numbers these tools show; what’s important is the relative volume of one keyword to another. Another good free tool is Google’s AdWords Keyword Tool, which doesn’t show exact numbers.

10. Open up a PPC account. Whether it’s Google’s AdWords or Yahoo’s Search Marketing or something else, this is a great way to get actual search volume for your keywords. Yes, it costs money, but if you have the budget it’s worth the investment. It’s also the solution if you didn’t like the “Be patient” suggestion above and are looking for instant visibility.

11. Use a unique and relevant title and meta description on every page. The page title is the single most important on-page SEO factor. It’s rare to rank highly for a primary term (2-3 words) without that term being part of the page title. The meta description tag won’t help you rank, but it will often appear as the text snippet below your listing, so it should include the relevant keyword(s) and be written so as to encourage searchers to click on your listing. Related bonus tip: You can ignore the Keywords meta altogether if you’d like; it’s close to inconsequential. If you use it, put misspellings in there, and any related keywords that don’t appear on the page.

12. Write for users first. Google, Yahoo, etc., have pretty powerful bots crawling the web, but to my knowledge these bots have never bought anything online, signed up for a newsletter, or picked up the phone to call about your services. Humans do those things, so write your page copy with humans in mind. Yes, you need keywords in the text, but don’t stuff each page like a Thanksgiving turkey. Keep it readable.

13. Create great, unique content. This is important for everyone, but it’s a particular challenge for online retailers. If you’re selling the same widget that 50 other retailers are selling, and everyone is using the boilerplate descriptions from the manufacturer, this is a great opportunity. Write your own product descriptions, using the keyword research you did earlier (see #9 above) to target actual words searchers use, and make product pages that blow the competition away. Plus, retailer or not, great content is a great way to get inbound links.

14. Use your keywords as anchor text when linking internally. Anchor text helps tells spiders what the linked-to page is about. Links that say “click here” do nothing for your search engine visibility.

15. Build links intelligently. Submit your site to quality, trusted directories such as Yahoo,DMOZ, Business.com, Aviva, and Best of the web. Seek links from authority sites in your industry. If local search matters to you (more on that coming up), seek links from trusted sites in your geographic area—the Chamber of Commerce, etc. Analyze the inbound links to your competitors to find links you can acquire, too.

16. Use press releases wisely. Developing a relationship with media covering your industry or your local region can be a great source of exposure, including getting links from trusted media web sites. Distributing releases online can be an effective link building tactic, and opens the door for exposure in news search sites. Related bonus tip: Only issue a release when you have something newsworthy to report. Don’t waste journalists’ time.

17. Start a blog and participate with other related blogs. Search engines, Google especially, love blogs for the fresh content and highly-structured data. Beyond that, there’s no better way to join the conversations that are already taking place about your industry and/or company. Reading and commenting on other blogs can also increase your exposure and help you acquire new links. Related bonus tip: Put your blog at yourdomain.com/blog so your main domain gets the benefit of any links to your blog posts. If that’s not possible, useblog.yourdomain.com.

18. Use social media marketing wisely. If your small business has a visual element, join the appropriate communities on Flickr and post high-quality photos there. If you’re a service-oriented business, use Yahoo Answers to position yourself as an expert in your industry. With any social media site you use, the first rule is don’t spam! Be an active, contributing member of the site. The idea is to interact with potential customers, not annoy them.

19. Take advantage of local search opportunities. Online research for offline buying is a growing trend. Optimize your site to catch local traffic by showing your address and local phone number prominently. Write a detailed Directions/Location page using neighborhoods and landmarks in the page text. Submit your site to the free local listings services that the major search engines offer. Make sure your site is listed in local/social directories such as CitySearch, Yelp, Local.com, etc., and encourage customers to leave reviews of your business on these sites, too.

20. Take advantage of the tools the search engines give you. Sign up for Google’s webmaster Central and Yahoo’s Site Explorer to learn more about how the search engines see your site, including how many inbound links they’re aware of.

21. Diversify your traffic sources. Google may bring you 70% of your traffic today, but what if the next big algorithm update hits you hard? What if your Google visibility goes away tomorrow? Newsletters and other subscriber-based content can help you hold on to traffic/customers no matter what the search engines do. In fact, many of the DOs on this list—creating great content, starting a blog, using social media and local search, etc.—will help you grow an audience of loyal prospects and customers that may help you survive the whims of search engines.

9
Jun

Top 12 CSS Frameworks

Most designers would have heard of the term ‘CSS Frameworks’, for those who don’t know or aren’t sure, here is a brief description from: Wikipedia:

A CSS framework is a library that is meant to allow for easier, more standards-compliant styling of a webpage using the Cascading Style Sheets language. Just like programming and scripting language libraries, CSS frameworks package a number of ready-made options for designing and outlaying a webpage. .

Sounds great doesn’t it, something that is going to make designing and developing a website that little bit easier. It will take away the repeating of the same old boring stuff and if you write your framework correctly you will be guaranteed your code will meet W3C recommendations. That will leave you plenty of time to design your site, the fun side of the job!

There are a number of Frameworks you can freely download and use, you will need a fair bit of CSS knowledge, some patience and a fair bit of time to get yourself familiar with the layout. The page layout structure is pretty standard across almost all Frameworks, it could be: Header; Main Content; Sub Content; Local Nav; Main Nav; Footer. They also have simple layout structures: Vertical Nav; Horizontal Nav; One Column; Two Column… The variations on structure goes on and on… Any structure you want, basically.

What I am trying to say is that if you are a serious designer/developer you need to use a good Framework, something that in the long term is going to save you a lot frustrations and time. Maybe you will or already have written your own Framework. I have my own, well two actually. One purely for WordPress and one for everything else. Not much difference in the two, but I do like to follow a particular method when designing for WordPress, just my preference.

There is a lot more to CSS Frameworks than I have written here, but I am not going to bore you, download them and try them out. If you don’t like it don’t use, its not for everyone. As with everything else in the world there are a few critics of CSS Frameworks, the pros do outnumber the cons, its all about opinion.
As for me I love them, and I am very grateful to the writers of the following ten CSS Frameworks:

12 of the best CSS Frameworks

1.Elements CSS Frameworks (Source: Project Designs)

2.WYMstyle: a CSS framework (Source: Daniel Reszka)

3.YAML CSS Framework (Source: High Resolution)

4.YUI Grids CSS (Source: Yahoo)

5.Boilerplate CSS Framework

6.Blueprint CSS

7.Schema Web Design Framework
(Source: David Golding Design)

8.CleverCSS

9.Tripoli Beta CSS Framework
(Source: Monc)

10.ESWAT Web Project Framework
(Source: Philip Karpiak)

11.CwS CSS Framework
(Source: Content with Style)

12.My (not really mine) CSS Framework
(Source: That Standards Guy)

25
May

Meta tags

Meta Title

An example of this tag looks like this.

1 <META NAME="Title" CONTENT="Page Title Here">

The title meta tag is used to set your webpage title, what ever you type inside the tag its displayed in the browser title bar or tab.

Meta Title

Meta Content Language

An example of this tag looks like this.

1 <META HTTP-EQUIV="Content-Language" CONTENT="en-GB">

This tag basically declares your webpage language, robots use this tag to assist non-US English sites in getting categorized properly by the search engines. You should only really use this tag if your website isn’t written in english.

Meta Keywords

An example of this tag looks like this.

1 <META NAME="keywords" CONTENT="photoshop, tutorials, learning">

The meta tag keywords are something you should definitely include into your website. It basically defines the content of your website and is very important for search engines. When there defined search engines use them to categorize your website.

Meta Content Type

An example of this tag looks like this.

1 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Meta content type is used to declare the character set of a website. It is recommended to always include this tag even if you use a DTD declaration above the header. If you don’t include it, it can cause your webpage to display incorrect. For example the Meta Content Type tag helps properly display the page if the document uses UTF-8 punctuation characters, but is displayed in ISO or ASCII character sets.

Meta Language

An example of this tag looks like this.

1 <META NAME="Language" CONTENT="english">

The language meta tag is used when declaring the language of your website, its use is to simply set the primary language.

Meta Copyright

An example of this tag looks like this.

1 <meta name="copyright" content="Copyright 2008">

The meta copyright tag is used if you want to include a copyright or trademark to your webpage. It is not required of you to use this tag, it doesnt protect you or your websites content in any way.

Meta Description

An example of this tag looks like this.

1 <META NAME="description" CONTENT="Adobe Photoshop Tutorials.">

This tag simply gives a short description of the current webpage, normally consisting of about 25 words or less. Search engines use the description tag on their search results pages. Normally there displayed underneath the title of your website.

Meta Description

Meta Designer

An example of this tag looks like this.

1 <META NAME="Designer" CONTENT="Your Name">

Meta designer is like an author tag, its normally used to declare the designer of the website, search engines dont use or need it when indexing your website but you could add it for advertising purposes or to catch out website rippers.

Meta Distribution

An example of this tag looks like this.

1 <META NAME="Distribution" CONTENT="Global">

This tag is used to declare the distribution of your content. It consists of three different attributes “global”, “local” and “IU”. Global means the entire web, local means to reserve for the local IP block of your website and IU means internal use, not for public distribution.

Meta Generator

An example of this tag looks like this.

1 <META NAME="Generator" CONTENT="Adobe Dreamweaver">

Although this tag serves no real purpose some applications like to include it. The tag generates the publishing tool name and/or version. If you notice it in your website delete it as like i said it serves no real purpose.

Meta Refresh

An example of this tag looks like this.

1 <META HTTP-EQUIV="Refresh" CONTENT="3;URL=http://www.yoursite.com/a-page.html">

The refresh meta tag is used to declare a delay in seconds before the browser automatically reloads the URL specified. An ideal example of this would be when you fill in a search form, on completion of the search form you are sent to a thank you page, the thank you page then redirects you back to the homepage.

Meta Robots

An example of this tag looks like this.

1 <META NAME="ROBOTS" CONTENT="NOINDEX,FOLLOW">

The meta robots tag controls the search engine robots, its recommended you not use this tag and instead control the search engine robots via the “robots.txt” file or the HTACCESS file.

24
May

Different Stylesheets for Differently Sized Browser Windows

Otherwise known as “resolution dependent layouts”. Single website, different CSS files for rearranging a website to take advantage of the size available.

There is a W3C standard way of declaring them. One way is to test the “device-width”, like this:

<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="http://13.cdn.blog.com/wp-admin/800.css" />

The above code will apply the 800.css styling to the document only if the device viewing it has a width of 800px or wider. And… supports “media queries” in this way.

Keep in mind this is the device width, not the current width of the browser window. On the iPhone (3G(s)), that means 480px. My fancy new MacBook Pro is going to return 1920px for the device width. But my actual browser window is only half of that at this exact moment. The device width is quite useful when dealing with mobile devices where the browser is probably 100% of the screen whenever in use, but less useful in laptop/desktop browsers.

Seems to me far more useful is the current width of the browser window (“viewport”). We can even specify stylesheets that are only to be used when the viewport is between two different pixel sizes:

<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='http://13.cdn.blog.com/wp-admin/css/medium.css' />

That stylesheet will only take affect when the current browser window is between 701 and 900 pixels in width.

Browser Support

Modern versions of Mozilla, WebKit, and Opera browsers all support this. Mozilla suggests starting the media attribute of the <link /> with “only” which will hide the stylesheet from older browsers that don’t support media queries. That may or may not be what you actually want to do… case dependent of course.

<link rel="stylesheet" media="only screen and (color)" href="http://13.cdn.blog.com/wp-admin/example.css" />

Internet Explorer (even 8) does not support this. I haven’t tested 9 yet, if anyone knows, let me know and I can update this.

Generally layout is one of those things that it’s tough to sell “progressive enhancement” on. Rounded corners becoming squares, no big deal. Messed up layout, that is a big deal. Devices like the iPhone right now are kind of great, since browser choice is so limited (there used to be just Mobile Safari and that’s it, now there is Opera as well) and they are very good browsers, you can rely on techniques like this to work.

If IE support is paramount, we always have JavaScript!

Doing it with jQuery

Using JavaScript, we can test the windows width and change the active CSS file accordingly. This will work across all browsers. You can have an ID for a <link /> element like any other, so let’s add that:

<link rel="stylesheet" type="text/css" href="http://13.cdn.blog.com/wp-admin/main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="http://13.cdn.blog.com/wp-admin/narrow.css" />

Then we can use that as a hook and change the href value of the stylesheet. The browser will see that change and unapply the old CSS and reapply the newly linked CSS. We’ll run our little adjustment test once right away, and then anytime the window is resized thereafter.

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css");
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

Is jQuery really necessary just for this?

No, but I’m sure you know that’s just how I roll in general and it makes it easier. Kevin Hale wrote about dynamic resolution layouts literally five years ago. It’s “raw” JavaScript and still works great today.

Video

Example One

This one has a special stylesheet for narrow (less than 700px), medium (701 – 900px), and wide (greater than 901px) browser windows.

View Demo

Example Two

This does the exact same thing as example one, only through jQuery/JavaScript instead of CSS media queries.

View Demo

Example Three

This example shows that we can target mobile devices by testing for a maximum device width.

View Demo

Download

Snag all of these for reference in one place.

Download Files