How to Design a Website with Fireworks: New Plus Tutorial

How to Design a Website with Fireworks: New Plus Tutorial

In this week’s plus video tutorial, we’ll teach you how to design a home page for a website using Adobe Fireworks CS4. Over the course of the video, you’ll learn numerous tips and tricks to accomplish the final design, including how to work with a grid. Help give back to Nettuts+, and join Plus!

In Depth Video Training

Video Example

Final Design

Final Product

Join Tuts Plus

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service called “TUTSPLUS”. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!

  • Subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.



Coding your First jQuery UI Plugin

Coding your First jQuery UI Plugin

jQuery contains the fn.extend() method, which makes authoring jQuery plugins quite easy, allowing us to write code that is used in exactly the same way as other jQuery methods. jQuery UI also contains structures that make authoring custom jQuery UI plugins easy. So that’s what we’ll be looking at over the course of this tutorial. The methods used differ from that of standard jQuery plugins, and there are stricter conventions that should be followed, which is why I feel the topic is deserving of an article.


Over the course of this tutorial, I’ll show you the coding conventions and general guidelines that should be adhered to when authoring plugins for jQuery UI. We’ll be creating a simple plugin that just adds captions to images on the page. It’s purposely simple so that we can focus on what is needed to make a jQuery UI plugin without getting lost in the code. Anyone that’s written a jQuery plugin should have no problems. Knowledge of jQuery UI may help but shouldn’t be essential to complete this tutorial. Let’s get started.

Getting Started

We’ll need a copy of jQuery as well as a couple of files from jQuery UI, but it needs to be jQuery UI 1.8 (this can be found on the blog). Create a working directory somewhere on your machine called jqueryui-plugin, then inside this create a css folder, a js folder and an img folder (the images used in this tutorial can be found in the code download).

Download the library and unpack it somewhere accessible. We only need a few files from the archive, namely the jQuery source file which is in the root of the archive as jquery-1.4.1.js, and the jquery.ui.core.js and jquery.ui.widget.js files, which are both in the ui folder. Grab these and put them into the js folder in your working directory. We’ll be making light use of the CSS framework as well, so we’ll need one of the theme style sheets available with the current stable version of jQuery UI (I used ui-lightness in this example).

We’ll be making a captionator widget, so we’ll also need a page, with a bunch of images on it, to develop/test the plugin with. This example uses the following page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>jQuery UI Captionator</title>
		<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.7.2.custom.css">
		<link rel="stylesheet" type="text/css" href="css/ui.captionator.css">
	</head>
	<body>
		<img src="img/1.jpg" alt="Royal Air Force Eurofighter Typhoon">
		<img src="img/2.jpg" alt="A British military GR-9 Harrier">
		<img src="img/3.jpg" alt="Two RAF Tornado GR-4s pull away from a KC-135 Stratotanker after refueling">
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript" src="js/jquery.ui.core.js"></script>
		<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
		<script type="text/javascript" src="js/jquery.ui.captionator.js"></script>
	</body>
</html>

We’ll keep things pretty simple for now; we’ve just three images on the page, followed by four script files; three link to the jQuery and jQuery UI source files, the fourth to our plugin’s source file which we’ll create shortly. The jquery.ui.core.js file is required by all jQuery UI widgets/plugins. The jquery.ui.widget.js file is the widget factory and allows for the creation of consistent widgets that share common API functionality. Most library components require this, and we’ll be using it to create our plugin.

Creating the Plugin File

Create a new JavaScript file and save it as jquery.ui.captionator.js in the js folder; we should keep to jQuery UI’s naming convention, which has just been updated in the 1.8 version of the library, and use jquery.ui.plugin_name.js. Add the following code to the new file:

(function($) {

})(jQuery);

All of the code that makes up our plugin should be encapsulated within a self-executing anonymous function. The jQuery object is passed into this function and is used inside the function via the $ alias; this is to ensure that the plugin is compatible with jQuery’s noConflict() method. This is a specified requirement and should always be adhered to.

Next we need to define the plugin; add the following code to our anonymous function:

$.widget("ui.captionator", {

});

The pattern for using the widget factory is simple to use, we just call the widget() method specifying the name of the plugin as the first argument, and an object literal containing the properties and methods that make the plugin function. This allows our plugin to be called (and created) using the commen jQuery syntax $(“element_caption_applied_to”).captionator(); like any other jQuery or jQuery UI method.

The widget factory provides a number of these properties and methods for us; for example, we can set the default options for the plugin using the options property, and add an initialisation function that is executed automatically by the widget factory as soon as an instance of the plugin is invoked. Within the object that appears as the second argument in the previous code add the following code:

options: {
  location: "bottom",
  color: "#fff",
  backgroundColor: "#000"
},

These are the only options we’ll use in our example plugin; users (and by users I mean implementers, not end users) of the plugin can specify the position of the caption to be either at the top of the image it is called on, or the bottom, they can specify the color of the text on the caption, or change the background-color of the caption. To change a configurable option of any jQuery UI widget prior to initialisation the implementing developer would just use something like this:

$(“element_caption_applied_to”).captionator({ location: “top” });

Next we can create our initialisation function, after the options object add the following method:

_create: function() {

	var self = this,
		o = self.options,
		el = self.element,
		cap = $("<span></span>").text(el.attr("alt")).addClass("ui-widget ui-caption").css({
			backgroundColor: o.backgroundColor,
			color: o.color,
			width: el.width()
		}).insertAfter(el),
		capWidth = el.width() - parseInt(cap.css("paddingLeft")) - parseInt(cap.css("paddingRight")),
		capHeight = cap.outerHeight() - parseInt(cap.css("paddingTop")) + parseInt(cap.css("paddingBottom"));

	cap.css({
		width: capWidth,
		top: (o.location === "top") ? el.offset().top : el.offset().top + el.height() - capHeight,
		left: el.offset().left,
		display: "block"
	});

	$(window).resize(function(){
		cap.css({
			top: (o.location === "top") ? el.offset().top : el.offset().top + el.height() - capHeight,
			left: el.offset().left
		});
	});
},

The method name should begin with an underscore as jQuery UI prevents any plugin method that begins with an underscore from being called from outside of the plugin, so this stops it being accidentally called from the HTML page. Any method that we begin with an underscore will be protected in this way.

The majority of our initialization method is a series of variables; within our function the keyword this refers to an object passed into the method which represents the instance of the plugin. The first variable caches a reference to the current instance of the plugin; the _create method is called for each element that the plugin method is called on, which could be a single element or several.

We can access the default options of the plugin (which are overridden automatically if the implementer configures any of them) using the options property of the object; we cache this in the second variable. The element that the plugin method (captionator()) was called on, which in this example would be an image, can be accessed using the element property of the object. We store this in the third variable.

We use the fourth variable to store a reference to the new caption element, which is built from a simple <span>; the <span> has its innerText set to the alt attribute of the current image, and several class names are added to it; we give it the ui-widget class name so that it can pick up some default styling from the current jQuery UI theme. We also give it a custom class name so that we can add some of our own styling.

Next we need to set some CSS properties; we’ll be using a separate style sheet for some styles, but certain things, such as the color and background-color styles are controllable via configurable options, so we need to set these using the plugin. The width of the caption needs to match the width of the image that it overlays, so we also need to determine this and set it programmatically. Finally the new <span> is injected into the page directly after the target image.

Once the caption has been inserted, it needs to be sized and positioned; the only way it can be sized accurately is if it already exists in the DOM and has CSS rules applied to it, such as the font-size. This is why we append the caption to the page, and then determine its exact dimensions, which are then stored in the variables capWidth and capHeight.

Once the caption has been appended to the page (and only then) we can work set the correct width, height and position of each caption, which we set using the css() method once again. The captions are actually completely separate from the images; they are inserted directly after each image and then positioned to appear to overlay the images, after all, we can’t append the <span> as a child of the <img>.

This is fine, until the browser is resized, at which point the images move but the captions don’t because they are absolutely positioned. To remedy this, we’ve used a basic resize handler attached to the window which simply repositions each caption to the new position of its image. This event handler is the last thing in our initialization method.

Another method that our plugin should expose is the destroy() method which is common to all jQuery UI plugins. We must provide an implementation of this method in order to clean up after our plugin. For our example plugin, the method can be as simple as this:

destroy: function() {
	this.element.next().remove();

	$(window).unbind("resize");
},

All we need to do is remove the captions and unbind our window resize handler. This method can be called by an implementer using the plugin so we shouldn’t begin this method name with an underscore. To call this method, the implementer would use $(“element_caption_attached_to”).captionator(“destroy”); which is how any of our public methods would be called.

We need to provide another method controlled/executed by the widget factory; we saw earlier how a developer could change a configurable option prior to initialisation, but what about after initialisation? This is done using the option method using the following syntax: $(“element_caption_attached_to”).captionator(“option”, “location”, “top”); so we need to add the built-in method _setOption to handle this:

_setOption: function(option, value) {
	$.Widget.prototype._setOption.apply( this, arguments );

	var el = this.element,
		cap = el.next(),
		capHeight = cap.outerHeight() - parseInt(cap.css("paddingTop")) + parseInt(cap.css("paddingBottom"));

	switch (option) {
		case "location":
			(value === "top") ? cap.css("top", el.offset().top) : cap.css("top", el.offset().top + el.height() - capHeight);
			break;
		case "color":
			el.next().css("color", value);
			break;
		case "backgroundColor":
			el.next().css("backgroundColor", value);
			break;
	}
}

We start this method with an underscore because the implementer uses option, not _setOption to actually change the options; we don’t need to worry about how this is handled, we just need to provide this method to deal with anything specific to our plugin. Because this method already exists in the widget factory we should call the original method, which we do first of all in our method using the prototype of the Widget object, specifying the method name (_setOption in this case but we could do it for other built-in methods as well) and use apply to call it. We can then proceed with the code specific to our plugin.

The function will automatically receive two arguments which are the option to change and the new value. We cache some commonly used elements, such as the image and the caption, and obtain the current height of each caption. We then use a simple switch-case statement to handle each of our three options being changed. Repositioning the captions is the most complex, but is still quite trivial and similar to how we positioned them initially.

Adding Events

It’s important to add events that developers using your plugin can add callbacks for so that they can react to different things happening when users interact with the widget in some way. The widget factory handles most of this task for us, all we need to do is trigger the event. This plugin doesn’t really do much, but we could still trigger an event after each caption is added to the page; to do this add the following code directly before the resize event handler:

self._trigger("added", null, cap);

That’s all we need to do! A single line of code and we have a custom event that can be reacted to. We call the _trigger() method of the plugin instance (which we stored in the variable self) and pass the method three arguments; the first is the name of the event, the second is for the event object (we don’t need to use this in our example plugin, hence the null value) and the third is a reference to the caption element. The widget factory will automatically pass the event object (if supplied) and the data we pass in the third parameter to a callback function that uses the added event. A developer could hook into this event using the following syntax: $(“element_caption_attached_to”).captionator({ added: function(e, ui){ //do stuff });

Styling the Plugin

We only need a very tiny style sheet for our plugin, literally we have just three styles. It’s almost not even worth creating a separate file for the styles! But we will, so create a new file called ui.captionator.css, which is the required format for plugin style sheets, and save it in the css directory. Add the following styles to it:

.ui-caption { display:none; position:absolute; padding:10px; }

That’s all there is to it. Our plugin is now functionally and visually complete. The captions should appear like this:

Final Product

Summary

Like jQuery’s plugin creation method fn.extend(), jQuery UI also has its own mechanism that allows developers to quickly and easily write robust and scalable plugins that meet the jQuery UI projects high standards, although in terms of what it actually does for us, it’s even better that jQuery. The widget factory has been created in such a way that pretty much all of the hard work is taken out of custom plugin creation.

It’s easy to work with the methods provided by the widget factory to add methods to our plugins that are common across UI widgets, such as the destroy and option methods, which implementing developers would expect to find in any plugin. We also saw just how easy it is to trigger custom events that developers can use to react to interactions or occurrences with the widget.

h3



.NET LINQ from Scratch

.NET LINQ from Scratch

As software developers, we spend a lot of time extracting and displaying data from many different data sources. Whether it’s a XML webservice of some sort, or a full featured relational database, we have been forced to learn different methods of data access. Wouldn’t it be great if the method of access was the same for all data sources? Well, we are in luck because, as of the release of C# 3.0 and the .NET 3.5 Framework, LINQ has come to change the game forever.

Tutorial Details

  • Introduction to LINQ syntax
  • Projections using LINQ
  • Refining data
  • Standard operators

Current Data Access Overview

On the .NET platform we have been and still are utilizing ADO.NET
for accessing different data sources. The open source community has also provided
the developers with a number of alternatives.

Language Integrated Query is the new addition to the .NET
family and as the name suggests it’s the kind of query style data access which
is fully supported by the language to effectively unify the way we access data
and to make our lives easier. LINQ is able to target a number of different sources namely Oracle,
MSSQL, XML and a few others, but for now we will focus on the most basic of
all, LINQ to Objects.

LINQ to Objects

Normally, to process and refine the data within our lists
and various other data structures, we have used either the ‘foreach’ loop or another
type of looping method to iterate through the objects and process them one by
one according to some condition. This is fine, but frankly it requires a lot of
basic coding that we all wish we didn’t have to write. Essentially we’ve had to tell the
compiler every single detail of the process in order to manipulate the data.

This is exactly where LINQ shines best. What LINQ allows us
to do is to simply tell the compiler what we’d like to perform and let the compiler work
out the best way to actually achieve that. If you’ve used SQL syntax before, the massive resemblances
between LINQ and any dialects of SQL will be the first thing that you’ll notice.
Like SQL, LINQ too supports the “select”, “from”, “where”, “join”, “group by”
and “order by” keywords. Here is a simple example of querying a list of objects:

List initialization:

List<Car> ListOfCars = new List<Car>()
{
    new Car {name = "Toyota"    , owner = "Alex" , model = 1992},
    new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
    new Car {name = "Land Rover", owner = "Danny", model = 2001},
    new Car {name = "BMW"       , owner = "Danny", model = 2006},
    new Car {name = "Subaru"    , owner = "Smith", model = 2003}
};

The query:

IEnumerable<Car> QueryResult = from car in ListOfCars
                               select car;

The first part of the preceding code simply populates a list
with four instance of the ‘Car’ class. The next part of the code, however, uses the
“from” and “select” keywords to select a group of objects. The main difference
between SQL and LINQ is that the “from” keyword comes before the “select”
keyword because we must first define the object we want to operate on. Finally
the “select” clause tells the compiler what we wish to extract in this query. The above
code simply extracts everything that is in the list and assigns it to the “QueryResult”
variable.

When we query things from objects (LINQ to Objects) our
queries always return an “IEnumrable<T>” list of objects. Essentially the
“IEnumerable” type is the kind of list that exposes the enumerator, which
supports a simple iteration over a non-generic collection, and <T>
is the type of each entry in the list.

Don’t worry if you aren’t familiar with “enumerators” and “generics”. Just
remember that the result of LINQ queries is always a collection like data
structure which allows for iterating through it using a loop like shown
bellow:

foreach(Car car in QueryResult)
    Console.WriteLine(car.name);

We learned that LINQ always returns a collection structure similar
to any other lists. However, the LINQ query does not execute until its result is
accessed by some other piece of code, like the “foreach” loop above. This is to
allow us to continuously define the query without the overhead by re-evaluating
each new step in the query.

Projections

So far so good; but most of the time, our queries will need
to be more complex; so let’s try projecting data. In SQL, Projection means selecting
the name of the column(s) of table(s) which one wishes to see appearing in the result
of the query. In the case of LINQ to Objects, performing Projection will result
in a different query result type than the type of object that we perform the
query on.

There are two kinds of Projections that we can do. We can
either perform a Projection based on an existing object type, or go completely
the other way by using anonymous types. The following example is of the first
kind:

IEnumerable<CarOwner> QueryResult = from car in ListOfCars
                                    select new CarOwner { owner_name = car.owner };

In the preceding code, the type of the query result is declared as
<CarOwner>, which is different to <Car>, the type that ‘ListOfCar’ variable is initialized with. We have
also used the “new” keyword and have done some assignments inside the curly
brackets. In the above code, using “select” with the “new” keyword tells the
compiler to instantiate a new ‘CarOwner’ object for every entry in the query result.
Also by assigning values to the new type we have initialized each instance
of the ‘CarOwner’ class.

Nonetheless, if you don’t already have a type defined to
use, you can still perform projections using anonymous types.

Projections using Anonymous Types

It would be a big hassle if, for every Projection, you were
forced to create a new type. That is why, as of C# 3.0, support for Anonymous
types was added to the language. An Anonymous type is declared using the “var”
keyword. It tells the compiler that the type of the variable is unknown until
it’s assigned for the first time.

var QueryResult = from car in ListOfCars
                  select new {
                      car_name = car.name,
                      owner_name = car.owner
                  };

foreach(var entry in QueryResult)
    Console.WriteLine(entry.car_name);

The above is an example of performing a query with Anonymous
types. The only catch to look out for is that the compiler will not
allow returning Anonymous types from methods.

Accessing the properties of an Anonymous type is easy. In Visual Studio 2008, the Code
Completion/Intellisense also lists the properties exposed by the Anonymous type.

Refining Data

Usually as part of the LINQ query, we also need to refine the
query result by specifying a condition. Just like SQL, LINQ too uses the “where”
clause to tell the compiler what conditions are acceptable.

IEnumerable<Car> QueryResult = from car in ListOfCars
                               where car.name == "Subaru"
                               select car;

The preceding code demonstrate the use of the “where” clause and
the condition to follow. To further to define multiple conditions, LINQ supports
the ‘and’ (&&amp) and ‘or’ (||) constructs. The “where” part of the query has to always be a
Boolean expression, otherwise the compiler will complain.

Order By

When querying objects, it’s possible to rely on the query
target being already sorted. If that isn’t the case, LINQ can take care of that
by using the “order by” clause which will ensure the result of your query is
properly sorted.

IEnumerable<Car> QueryResult = from car in ListOfCars
                               orderby car.model
                               select car;

If you run the above code, you’ll see that the result of the
query is sorted in ascending order. You can alter the order by using the “ascending” and “descending”
keywords, and further change the order by specifying more than one field to sort
by. The following code shows how:

IEnumerable<Car> QueryResult = from car in ListOfCars
                               orderby car.model descending
                               select car;

Grouping

LINQ also allows grouping the query result by the value of a
specific property as shown in this example:

var QueryResult = from car in ListOfCars
                  group car by car.owner into carOwnersGroup
                  select carOwnersGroup.Key;

As you can see, LINQ supports the “group by” clause to
specify what object and by what property to group by. The “into” keyword will
then allow us to project on a grouping result which can be accessed by the “Key”
property.

Joins

LINQ supports joining data from different collections into one
query result. You can do this using the “join” keyword to specify what objects
to join and use the “on” keyword to specify the matching relationship between
the two objects.

Initializing related list:

List<Car> ListOfCars = new List<Car>()
{
    new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
    new Car {name = "Land Rover", owner = "Danny", model = 2001},
    new Car {name = "Subaru"    , owner = "Smith", model = 2003},
    new Car {name = "Toyota"    , owner = "Alex" , model = 1992},
    new Car {name = "BMW"       , owner = "Danny", model = 2006},
};

List<CarOwner> ListOfCarOwners = new List<CarOwner>()
{
    new CarOwner {owner_name = "Danny", age = 22},
    new CarOwner {owner_name = "Jeff" , age = 35},
    new CarOwner {owner_name = "Smith", age = 19},
    new CarOwner {owner_name = "Alex" , age = 40}
};

Query:

var QueryResult = from car in ListOfCars
                  join carowner in ListOfCarOwners on car.owner equals carowner.owner_name
                  select new {name = car.name, owner = car.owner, owner_age = carowner.age};

In the above code, using an Anonymous type, we have joined
the two objects in a single query result.

Object Hierarchies using Group Joins

So far, we’ve learned how we can use LINQ to build a flat
list query result. With LINQ, it’s also possible to achieve a hierarchical query
result using “GroupJoin”. In simple words, we could assign objects to
properties of every entry with LINQ query.

List<Car> ListOfCars = new List<Car>()
{
    new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
    new Car {name = "Land Rover", owner = "Danny", model = 2001},
    new Car {name = "Subaru"    , owner = "Smith", model = 2003},
    new Car {name = "Toyota"    , owner = "Alex" , model = 1992},
    new Car {name = "BMW"       , owner = "Danny", model = 2006},
};

List<CarOwner> ListOfCarOwners = new List<CarOwner>()
{
    new CarOwner {owner_name = "Danny", age = 22},
    new CarOwner {owner_name = "Jeff" , age = 35},
    new CarOwner {owner_name = "Smith", age = 19},
    new CarOwner {owner_name = "Alex" , age = 40}
};

var QueryResult = from carowner in ListOfCarOwners
                  join car in ListOfCars on carowner.owner_name equals car.owner into carsGroup
                  select new {name = carowner.owner_name, cars = carsGroup};

foreach(var carOwner in QueryResult)
    foreach(var car in carOwner.cars)
        Console.WriteLine("Owner name: {0}, car name: {1}, car model: {2}", carOwner.name, car.name, car.model);

In the above example, the “Join” clause is followed by an “into”
part. This differs to the previous join operation that we looked at. Here, the “into”
clause is used to group cars by the owner (into carsGroup) and assign the grouping to the
“cars” property of the anonymous type.

Standard Query Operators

Thus far, everything that we’ve seen has been supported by the C# 3.0
syntax. However, there is still a large number of operations that C# 3.0 does not
support. The standard query operators provide query capabilities including
filtering, projection, aggregation, sorting and more. These operations are therefore supported
as methods of the LINQ library and can be executed on result of a query like shown in the
following screenshot:

These operators are listed below for your reference.

Aggregate Operators

  • Sum: returns the sum of all entries
  • Max: returns the entry with the maximum value
  • Min: returns the entry with the minimum value
  • Average: returns the average value for the collection
  • Aggregate: used for creating a customized aggregation
  • LongCount: when dealing with a large collection, this method will return a value up to the largest value supported by the “long” class
  • Count: returns an “integer” for the count of items in the collection

Element Operators

  • First: returns the first entry from the result collection
  • FirstOrDefault: if empty collection, will return the default value, otherwise will return the first entry from the collection
  • Single: will return only element from the collection
  • SingleOrDefault: if empty collection, will return the default value, otherwise will return only element from the collection
  • Last: returns the last entry from collection
  • LastOrDefault: if empty collection, will return the default value, otherwise returns the last entry from collection
  • ElementAt: returns the element at the specified position
  • ElementAtOrDefault: if empty collection, will return the default value, otherwise returns the element at the specified position

Set Related Operators

  • Except: similar to the left join in SQL, will return entries from the one set that doesn’t exist in another set
  • Union: returns all entries from both objects
  • Intersect: returns the same elements from either sets
  • Distinct: returns unique entries from the collection

Generation Operators

  • DefaultIfEmpty: if result is empty, returns default value
  • Repeat: repeats on returning objects for specified number of times
  • Empty: will return an empty IEnumerable collection
  • Range: returns a range of numbers for a specified starting number and count

Refining Operators

  • Where: will return objects that meet the specified condition
  • OfType: will return objects of the specified type

Conversion Operators

  • ToLookup: returns the result as a lookup
  • ToList: returns the result as a List collection
  • ToDictionary: returns the result as a dictionary
  • ToArray: returns the result as an Array collection
  • AsQueryable: returns the result as a IQueryable<T>
  • AsEnumerable: returns the result as a IEnumerable<T>
  • OfType: filters the collection according to the specified type
  • Cast: used to convert a weakly typed collection into a strongly typed collection

Partitioning Operators

  • Take: returns a specified number of records
  • Takewhile: returns a specified number of records while the specified condition evaluates to true
  • Skip: skips specified number of entries and returns the rest
  • SkipWhile: skips specified number of entries while the specified condition evaluates to true

Quantifier Operators

  • Any: returns true or false for a specified condition
  • Contains: returns true or false for existence of the specified object
  • All: returns true or false to all objects meeting the specified condition

Join Operators

  • Join: returns entries where keys in sets are the same
  • GroupJoin: used to build hierarchical objects based on a master and detail relationship

Equality Operators

  • SequenceEqual: returns true when collections are equal

Sorting Operators

  • Reverse: returns a reversed collection
  • ThenBy: used to perform further sorting
  • ThenByDescending: used to perform further sorting in descending order
  • OrderBy: used to define order
  • OrderByDescending: used to define descending order

Projection Operators

  • SelectMany: used to flatten a hierarchical collection
  • Select: used to identify the properties to return

Concatenation Operators

  • Concat: used to concatenate two collections

So What Now?

LINQ has proven itself to be very useful for querying objects, and the SQL-like syntax makes it easy to
learn and use. Also, the vast number of Standard Operators makes it possible to chain a number of operators
to perform complex queries. In a follow-up to this tutorial, we’ll review how LINQ can be used to
query databases and XML content..

Sell .NET Scripts and Components on CodeCanyon



Quick Tip: Private Variables in JavaScript

Quick Tip: Private Variables in JavaScript

Because of JavaScript’s dependence upon globals, it might be easy to forget that creating private variables can be accomplished quite simply, thanks to closures. In just a few minutes, I’ll demonstrate two common techniques which allow for private variables and methods in your projects.

The key to this particular method is to create a variable that is equal to the returned value of a function. That way, we can specifically choose with values and methods are available to our object. Thanks to closures, we’ll still have access to these private variables, even after the object has been returned from our singleton.

var MyObj = function() {

// Private variables
  var priv1 = 'private 1',
      priv2 = 'private 2';

// Only the methods and properties within this object will be available.
  return {
    doSomething : function() {
      // alert(priv1); // private 1
      alert(this.someProp); // someValue
    },

    someProp : 'someValue'
  }

}(); // execute the function when the MyObj variable is initialized.

  MyObj.doSomething();

View a live demo.



CSS Fundamentals: CSS 3 Transitions

CSS Fundamentals: CSS 3 Transitions

As CSS3 rolls out around the web, it is bringing some interesting new presentational techniques along with it. Today, we’ll review the basics of using CSS3 transitions and animations to add an extra layer of polish.


Tutorial Details

  • Program: A web browser that can utilise CSS3 transistions (Chrome or Safari)
  • Language: CSS
  • Difficulty: Easy
  • Estimated Completion Time: 30 min

Prefer a Video Tutorial? Join Plus!

If you’re more of a visual learner, you can watch a video version of this article instead. Simply help give back to Nettuts+ by signing up for a Plus membership, which grants you access to the Plus content for ALL of our sites – all for $9 per month.

Already a Member?

Watch the video version of this tutorial.

Step 1 – Link Transitions

To begin, we’ll work with some basic techniques – firstly a simple change of text color when a user hovers over a specified element.

a { color:#000; }
a:hover { color:#f00; }

Here, we change the text color to red on hover. Now, with a little CSS3, we can create a much smoother look by gradually fading the color.

a{
   color:#000;
   -webkit-transition:color 1s ease-in;
}
a:hover{color:#f00;}

We’ve added the css property, -webkit-transition. Note that the -webkit prefix specifies that this will only work in Webkit engines, or Safari and Chrome. Luckily, other modern browsers have their own implementations as well. A full statement covering all browsers might look similar to the following:

a {
   color:#000;
   -webkit-transition:color 1s ease-in;
   -moz-transition:color 1s ease-in;
   -o-transition:color 1s ease-in;
   transition:color 1s ease-in;
}

Please note that, for this tutorial, we’ll be focusing exclusively on the webkit implementation. After the declaration of the property, we have the values “color 1s ease-in.” This is the shorthand declaration; the three values represent:

  1. the property to be transitioned
  2. the duration of the transition
  3. the type of transition

In this case, we transition using ease-in, which will begin the transition slowly, and speed up into the transition.

Step 2. Background Transitions

Another basic use of changing states is to change the background of an input box on focus.

input.ourInputBox:focus{
 -webkit-transition:background-color 0.5s linear;
 background:#CCC;
}

This time, we put the transition declaration into the hover state, so that we aren’t adding additional unnecessary classes to the CSS. We apply the transition once the input box acquires focus.

Step 3 – Transitioning Multiple Properties

CSS transitions are actually relatively straight forward to add to existing hover functionality, and give your
site that extra polish for browsers that support CSS3.

To take things a step further, we can also transition multiple CSS properties using the longhand versions of the CSS3 transition.

a.thebg {
 color:#000;
 background:#f00;
 padding:5px;
 -webkit-border-radius: 5px; 

 -webkit-transition-property:color, background;
 -webkit-transition-duration: 1s, 1s;
 -webkit-transition-timing-function: linear, ease-in;
} 

a.thebg:hover {
 color:#f00;
 background:#000;
}

This time, the background and text color changes on hover, so we can target both of these properties with our transition.
We simply split the transition: first we have -webkit-transition-property and separate the different values with a comma. So we target the color and background properties, respectively.

-webkit-transition-property:color, background;

Then we set the duration of the transition using:

-webkit-transition-duration:1s, 1s;

These are referenced in the same order as the first statement; this time, however, both values are set to 1s.

Lastly, we set the timing function, and set two different values: the first, linear, relates to our first declared variable – color; and the second relates to the variable background.

So, we’ve set the color to a linear change over one second, and the background to ease-in over that same time period.

Step 4 – Putting the Pieces Together

CSS3 transitions start to come into their own when they’re combined with other new CSS properties.

You can review examples of using overlapping elements and transitions on Andy Clarke’s For a Beautiful Web.

Let’s create a simple example of animating a pop out sign.

We first create the bounding box for the signpost, and give it a relative positioning context to ensure that we can
position items absolutely within it.

#signpost{
 width:60px;
 height:196px;
 position:relative;
}

Now we place the box on the page and put the pieces of our sign within it.

<div id="signpost">
	<img id="post" src="post.png">
	<img id="sign" src="sign.png">
</div>

Next, the post is positioned with a z-index of two, to place it on top of the sign.

#post{
 width:79px;
 height:196px;
 z-index:2;
 position:relative;
}

Now, we add in the sign, positioned underneath the post, and rotate it with the CSS3 transform property.

#sign{
 height:46px;
 width:80px;
 position:absolute;
 top:10;
 left:60;
 -webkit-transform-origin:0 0;
 -webkit-transform: rotate(86deg);
 z-index:1;
 -webkit-transition:-webkit-transform 0.5s ease-in-out;
}

The sign is rotated using -webkit-transform: rotate(86deg), and is positioned under the post. To ensure that the sign rotates around the proper point, we must change the transform origin to the top left corner: 0, 0.

We set the transition to change the -webkit-transform property over 0.5s with an ease-in-out profile, and on hover, we rotate the sign back to its original orientation.

#signpost:hover #sign{
	-webkit-transform:rotate(0deg);
}

We do this on the containing #signpost:hover rather than on the hover of the #sign itself.

Step 5 – Introducing Animations

We can now tie all of this together, using webkit animations, which give us the power to carry out things such as continuous rotation.

We begin by creating two circle images, and positioning them inside a containing div – as we did with the signpost above.

<div id="circles">
	<img src="outer.png" width="180" height="180" class="outercircle"/>
	<img src="middle.png" width="90" height="90" class="middlecircle"/>
</div>
#circles{
	width:180px;
	height:180px;
	position:relative;
}
.outercircle{
	width:180px;
	height:180px;
	position:absolute;
	z-index:1;
	top:0:
	left:0;
}
.middlecircle{
	width:90px;
	height:90px;
	position:absolute;
	z-index:3;
	top:45px;
	left:45px;
}

Now we need to define the animations; we’ll spin the circles in opposite directions, so we need to set up two animations.

@-webkit-keyframes spin {
from {
	-webkit-transform: rotate(0deg);
}
to {
	-webkit-transform: rotate(360deg);
	}
}

@-webkit-keyframes spinrev {
from {
	-webkit-transform: rotate(0deg);
	}
to {
	-webkit-transform: rotate(-360deg);
	}
}

The animation is given a name for reference, in this case “spin” and “spinrev.” Then, we assign them a to and from value; so we rotate the image from
0 deg to 360 deg using webkit transform, and to -360 for the reverse.

Now we assign this animation to the hover states. Note that, if we assigned it to the normal state, the animation would run immediately when the page is loaded.

#circles:hover .outercircle {
	-webkit-animation-name: spin;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-timing-function: linear;
	-webkit-animation-duration: 10s;
}	

#circles:hover .middlecircle{
	-webkit-animation-name: spinrev;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-timing-function: linear;
	-webkit-animation-duration: 5s;
}

We reference the animation name we created earlier (-webkit-animation-name: spin;). Then, we declare the number of times we want the animation to run (-webkit-animation-iteration-count: infinite;).
In this case, infinite will keep it going round and round whilst the #circles div is hovered upon.

We next set the timing function (-webkit-animation-timing-function: linear;), and, finally, we set a duration for each iteration – in this case, it will be ten seconds (-webkit-animation-duration: 10s;), and five for a complete revolution.

Step 6 – Graceful Degredation with Modenizr

Once we have everything working, we should consider our users who are browsing without CSS3 capable web browsers. This is easily accomplished using a JavaScript library such as Modernizr, which adds classes to the HTML element relating to the browser capabilities.

Using the sign post example above, browsers that don’t support CSS transforms will not place the sign under the post correctly; so we can target these browsers and simply hide the sign until it is hovered over.

.no-csstransforms #signpost #sign{
	display:none;
}
.no-csstransforms #signpost:hover #sign{
	display:block;
}

It’s as simple as linking to the Modernizr script, finding the appropriate class name, and then creating a separate CSS statement for that instance.

Conclusion

That’s all for now. I hope you enjoyed it! Let me know if you have any questions/comments below!

You Also Might Like



Server Issues

Server Issues

Over the weekend and into Monday we unfortunately experienced some pretty severe downtime on all Envato WordPress blogs. The downtime was due to problems in the data centre of our current hosting company which was out of our control.

It seems to all be resolved now, but I just wanted to make a quick apology for the inconvenience and interruptions. We’re going to be re-examining our hosting setup to make sure we avoid this situation in the future and to generally try to pull up the quality of service across the board.

In the meantime there may be some further minor interruptions as we shore up the setup. Thank you for your patience!



One Week Left to Enter the CodeCanyon Scripting Competition

One Week Left to Enter the CodeCanyon Scripting Competition

On February 1st, we announced an enormous scripting competition on CodeCanyon with prizes equaling $6200. You now have just one week left to enter!

For those unfamiliar, Envato recently launched its newest marketplace, focused specifically on selling high-quality scripts and components for PHP, JavaScript, ASP.NET, and Java. As we’ve only recently launched, we’re hoping to build up our repository with a plethora of fantastic scripts and components, across all of the categories.

How Do I Enter?

Quite simply! To enter, prepare an item (PHP, JS, ASP.NET, or Java) of your choice for CodeCanyon, and once it has been submitted and accepted on the site, leave a comment here with a link to your item. That way, we can track it! That’s all! Then, on March 1st, 2010 (CST), my review staff and I will filter through all of the submissions and choose the best three of the bunch!

Grand Prize Winner

  1. 1 Dedicated Virtual Box (Rage) from Media Temple ($1200 value)
  2. 1 32 gigabyte iPod Touch ($299 value) (Ultimate TechSmith Package)
  3. 1 copy of Camtasia Studio for Mac or PC ($299 value) (Ultimate TechSmith Package)
  4. 1 copy of Camtasia Studio 6: The Definitive Guide ($39.95 value) (Ultimate TechSmith Package)
  5. 1 Logitech QuickCam Communicate Deluxe PC Webcam ($99 value) (Ultimate TechSmith Package)
  6. 1 Audio Technica USB Studio Condenser Microphone ($149 value) (Ultimate TechSmith Package)
  7. $100 Envato credit (Can be used across all of the marketplaces)
  8. $200 cash
  9. 1 MediaTemple Gift Card – 1 year of hosting, 1 domain name, Up to 5 websites. ($95 value)
  10. $25 Amazon Gift Card
  11. 1 year Tuts Plus membership – ($78 value)
  12. 1 Wufoo Subscription – 1 year ($288 value)
  13. 1 Formspring Pro Subscription – 1 year ($348 value)
  14. 1 Surreal CMS Subscription – 1 year ($275 value)
  15. 1 Personal TypeKit subscription – 1 year ($300 value)
  16. 1 Myows Paid AccountFREE for life
  17. 1 Rockable Press Book of your Choice ($29 value)
  18. 1 copy of Snippet (mac app) ($13 value)
  19. 1 copy of jQuery UI 1.7 from Packt Publishing ($40.49 value)
  20. 1 copy of Magento Beginner’s Guide from Packt Publishing ($35.99 value)
  21. 1 copy of Object-Oriented JavaScript from Packt Publishing ($35.99 value)
  22. 1 copy of jQuery Cookbook from O’Reilly Publishing ($34.99 value)
  23. 1 Threadsy Invite
  24. You will be featured on the front page of CodeCanyon as both the featured author and the featured item of the week!
  25. Your item will be included in a collection of the three winning submissions, and will be promoted on the front page of CodeCanyon
  26. As an Envato marketplace author, you’ll earn 40-70% of every sale!

2 Runners-Up

  1. 1 year Tuts Plus membership – ($78 value)
  2. $50 Envato credit
  3. 1 Personal TypeKit subscription – 1 year ($300 value)
  4. 1 Surreal CMS Subscription – 1 year ($275 value)
  5. 1 Wufoo Subscription – 1 year ($288 value)
  6. 1 Myows Paid AccountFREE for life
  7. 1 Rockable Press Book of your Choice ($29 value)
  8. 1 copy of Snippet (mac app) ($13 value)
  9. 1 Threadsy Invite
  10. Your item will be included in a collection of the three winning submissions, and will be promoted on the front page of CodeCanyon
  11. As an Envato marketplace author, you’ll earn 40-70% of every sale!

What Kind of Item Should I Submit?

We’ll that’s entirely up to you! That’s where you get to be creative. With that said, you’ll want to think of an item that will appeal to a wide variety of buyers. Ask yourself, “what sort of script or component – that’s not widely available around the web for free – have I often found myself in need of? Remember that, at this time, we’re only accepting PHP, JavaScript, ASP.NET, and Java related items.

Refer here to view the best selling items on CodeCanyon.

FAQs

When is the deadline to enter?

The competition will officially end on February 28th, 2010 at 11:59 PM, Central Standard Time. However, we do hope that you’ll submit before that date.

Are all items accepted on CodeCanyon?

No. You’ll first go through a review process, similar to all of our other marketplaces. It’s possible that your item will be rejected, in which case, it won’t be considered.

How Will you Judge?

We’ll consider many factors when determining the winners: overall sales, innovation, how much it appeals to a wide variety of buyers, etc.

Who Will be Judging?

The CodeCanyon review staff will collaborate to determine the winners.

Terms and Conditions

  • Envato staff and reviewers are not eligible to compete
  • Only items uploaded between 12:01 AM 02/01/2010 and 11:59PM 2/28/2010 CST and subsequently approved for sale on CodeCanyon are eligible to count.
  • The same author cannot win more than once. In other words there will be three winners, no less.
  • Our decision is final.
  • Files that are taken down for any reason are not eligible to be counted.
  • Files must stay up on CodeCanyon for at least 6 months.
  • Items may not be substituted for their cash equivalent.
  • Prizes will be awarded during the first week of March, to give time to ensure no copyright infringement has occurred.

So get coding! There are five-thousand reasons to do so! We can’t wait to see what you come up with.



CodeIgniter from Scratch: File Uploading and Image Manipulation

CodeIgniter from Scratch: File Uploading and Image Manipulation

In lesson nine of our CodeIgniter series, we’ll build a small image gallery that allows you to upload files, and automatically create thumbnails.

Final Example

Catch Up

Day 9: File Uploading and Image Manipulation

Other Viewing Options



ASP.NET for PHP Developers: Part 2

ASP.NET for PHP Developers: Part 2

In part one of the “ASP.NET for PHP Developers” tutorial, we learned the basics of ASP.NET and the C# language. Part two builds on that foundation, and introduces some more advanced features and techniques to take your ASP.NET pages to the next level.

Tutorial Details

  • Technology: ASP.NET (C#)
  • Difficulty: Advanced
  • Estimated Completion Time: 1 hour
  • Part: 2 of 2

Before you Start…

Ensure you have read and completed the examples in part 1 of the tutorial. We’ll be building on that application here. It’s also worth stressing that you need a good grasp of object oriented programming (OOP) to continue.

And Before I Start…

I mentioned in part 1 of the tutorial that there are two flavours of ASP.NET available:

  • ASP.NET WebForms: the original framework allowing developers to create web applications using many of the same techniques used in .NET Windows desktop applications
  • ASP.NET MVC: a newer framework offering Model-View-Controller architecture and more control over client-side code

However I don’t use either of those, but rather a third approach of my own devising. That’s for several reasons:

  1. When I started writing serious ASP.NET applications I retained my high standards of HTML output learned when writing PHP. If the page didn’t validate I felt dirty. There are a lot of developers who feel the same. ASP.NET WebForms gave, at the time, awful markup for many of the standard controls, so I had to come up with another solution. Adding runat="server" to HTML elements offered many of the advantages of true ASP.NET controls, but gave me full control over the HTML that was outputted. Things improved, and are looking even better for ASP.NET 4.0.
  2. I saw lots of examples of ASP.NET code where it was obvious the developer didn’t care about the resulting HTML. Perhaps they were Windows desktop application developers making the jump to the web, maybe they had never hand-coded HTML. Whatever the reason, I determined I would not be one of them.
  3. Quite a few of the standard ASP.NET controls relied entirely on JavaScript which is, to be frank, unforgivable for public websites (in the UK web accessibility is a legal requirement). For example, the evil javascript:__doPostBack function is a perfect way to make your website impossible to use for a large proportion of the web audience – oh, and search engines as well.
  4. I wanted to use my own choice of JavaScript library (initially Prototype, but then jQuery, now officially supported by ASP.NET). If I had to use the ASP.NET framework JavaScript library it would have made that more difficult.
  5. So why not ASP.NET MVC? Well, it wasn’t around when I started writing ASP.NET applications, and even if it was it would have been another hurdle to jump to get anything to work. Learning the .Net framework and C# language was challenging enough!

So you can see why I chose this "roll-your-own" approach. As ASP.NET matured and I discovered new features, I started to integrate those into my applications, and I fully expect that over time I’ll be doing more of that.

So, let’s take our ASP.NET application to the next level.

Master Pages

My second favourite feature of ASP.NET (after turning HTML controls into server controls) is master pages. A master page is a template file you can use to encapsulate HTML you use in multiple pages. For example, your master page could contain the header, menu and footer of your pages, while your normal .aspx pages contain the actual content on that page. let’s look at an example web page:

A sample web page

You can see the parts which are used on multiple pages highlighted in green. The content which changes for each page in the site is highlighted in red. Master pages allow us to split up the code for these two sections into multiple files. If you’ve used templates in your PHP applications (for example WordPress has header.php, footer.php and sidebar.php) you’ll see how great master pages are.

Creating a master page

So let’s create a master page. In the Solution view create a new directory in your ASP.NET application called "Master_Pages". In that directory create a new master page by right-clicking on the Master_Pages folder, selecting "Add > New file" then selecting "Master Page with Code Behind" and call it "DefaultMaster". Your new master page will be created and you’ll see the "DefaultMaster.master", "DefaultMaster.master.cs" and "DefaultMaster.master.designer.cs" files in the Master_Pages folder.

A new master page in MonoDevelop

Open the "DefaultMaster.master" and "DefaultMaster.master.cs" files. The code-behind file (.cs) for the master page (.master) works exactly the same as the code-behind file for an .aspx page. The first thing to note is master pages do not inherit from System.Web.UI.Page like .aspx pages do. Instead they inherit from System.Web.UI.MasterPage. Here’s the default code for the code-behind.

using System;
using System.Web;
using System.Web.UI;
namespace WebApplication1
{
	public partial class DefaultMaster : System.Web.UI.MasterPage
	{
	}
}

And for the .master file itself:

<%@ Master Language="C#" Inherits="WebApplication1.DefaultMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
	<title>DefaultMaster</title>
</head>
<body>
<div id="container">
<form runat="server">
    <asp:contentplaceholder id="contentPlaceHolder" runat="server" />
</form>
</div>
</body>
</html>

Because we’re not using the WebForms model, let’s quickly remove the tags for the <form runat="server"> element.

You should be getting used to page declarations (the <%@ Page ... %> bit in .aspx pages) by now, so the <%@ Master ... %> declaration will come as no surprise. What is different in this code is a new control: <asp:contentplaceholder>.

<asp:contentplaceholder id="contentPlaceHolder" runat="server" />

This content placeholder is where the content from your .aspx pages will be inserted. You can have as many of these in a .master page as you like.

Referencing your master page

Let’s go back to our normal .aspx page and make some edits. The first thing to do is remove the <html>, <head> and <body> tags, as they will now be in the master page. That leaves:

<%@ Page Language="C#" Inherits="WebApplication1.Default" %>

<h1 id="headertext" runat="server">This is the text</h1>

Now we need to specify what content to place in the content placeholder. We do that by specifying where the master page is, and wrapping our content in an asp:Content control, like this:

<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %>
<asp:Content id="Content1" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<h1 id="headertext" runat="server">This is the text</h1>
</asp:Content>

There’s a couple of things to note here. Firstly the Page declaration has an additional attribute of "MasterPageFile" with a value of "~/Master_Pages/DefaultMaster.master". In ASP.NET "~" means the root of the application, the rest of that path just points to our master page.

Secondly you see the new asp:Content control has an attribute of "ContentPlaceHolderID" with a value of "contentPlaceHolder", which is the "id" attribute of our <asp:contentplaceholder>. Running the application will give you:

An ASP.NET master page and content page working together

Checking the source code of the page proves that the master page (.master) and content page (.aspx) have been seamlessly integrated together. Now you see why I love master pages so much.

A more complex master page

We can push master pages a lot further than this simple example. Let’s have a go at building something that looks more like a real web application, starting with the master page. Firstly we’ll add some more content placeholders and a few server-side controls:

<%@ Master Language="C#" Inherits="WebApplication1.DefaultMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
	<title><asp:contentplaceholder id="PageTitle" runat="server" /></title>

	<script src="scripts/jquery.min.js"></script>
	<asp:contentplaceholder id="PageJS" runat="server" />

	<link rel="stylesheet" href="styles/default.css"></link>
	<asp:contentplaceholder id="PageCSS" runat="server" />
</head>
<body>
<div id="container">

	<h1 id="sitename" runat="server"></h1>

	<ul id="menu">
		<li><a href="about.aspx">About me</a></li>
		<li><a href="services.aspx">My services</a></li>
		<li><a href="contact.aspx">Contact me</a></li>
	</ul>

	<div id="content">
		<asp:contentplaceholder id="PageContent" runat="server" />
	</div>

	<div id="footer">
		<p id="copyright" runat="server"></p>
	</div>

</div>
</body>
</html>

And in the code-behind file for our master page we’ll put:

using System;
using System.Web;
using System.Web.UI;
using System.Configuration;

namespace WebApplication1
{
	public partial class DefaultMaster : System.Web.UI.MasterPage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			sitename.InnerHtml = ConfigurationSettings.AppSettings["SiteName"];
			copyright.InnerHtml = ConfigurationSettings.AppSettings["CopyrightNotice"] + DateTime.Now.Year.ToString();
		}
	}
}

(I’ll leave it as an exercise for you to add the SiteName and CopyrightNotice applications settings to web.config.)

Now for our content page. We have four content placeholders we can use: PageTitle, PageJS, PageCSS and PageContent. Here’s the code for the .aspx content page:

<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %>

<asp:Content id="PageTitle" ContentPlaceHolderID="PageTitle" runat="server">
	<asp:Literal id="Title" runat="server"></asp:Literal>
</asp:Content>

<asp:Content id="PageCSS" ContentPlaceHolderID="PageCSS" runat="server">
<style type="text/css">
h1 {
	font-family: sans-serif;
	color: #090;
}
</style>
</asp:Content>

<asp:Content id="PageContent" ContentPlaceHolderID="PageContent" runat="server">

	<h2>Welcome, one and all</h2>
	<p>This is my very first ASP.NET website, working with a master page!</p>

</asp:Content>

And the code-behind for our .aspx content page:

using System;
using System.Web;
using System.Web.UI;
using System.Configuration;

namespace WebApplication1
{
	public partial class Default : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			Title.Text = "Welcome to my first ASP.NET Website";
		}
	}
}

A couple of new things to notice here. Firstly I haven’t used the PageJS content placeholder at all – it’s quite OK to leave it out entirely (of course nothing will be rendered to the page for that area). Secondly I’ve introduced another ASP.NET control, namely <asp:Literal>, which we’ll take a quick look at now.

The Literal control

The Literal control is very useful when you want to render something to the page without any extra markup. For example, a lot of the time it’s fine to use:

<span id="message" runat="server"></span>

message.InnerHtml = "This is the message"

Gives:

<span id="message">This is the message</span>

But if you don’t want the span tags at all, for example for the page <title>, you need the Literal control. Setting the "Text" property of the Literal control renders just that text to the page:

<asp:Literal id="message" runat="server"></asp:Literal>

message.Text = "This is the message";

Gives:

This is the message

The completed master and content page

So running our application should give us this:

An ASP.NET master page and content page with multiple content placeholders

This is really just scratching the surface, as it’s possible to have multiple master pages (even nested master pages!). You can also set the master page programatically (but this needs to be done in the Page_Init event, as Page_Load is too late in the page lifecycle). There’s lots more detail about MasterPages on the MSDN site.

Custom Classes

It’s possible to create custom classes in your application, just like you would in PHP. Let’s create a security class by right-clicking the root of your application and selecting "Add > New file" then choosing "Empty class" from the "General" section and calling it "Security".

An new empty class

The code for your new class looks like this:

using System;
namespace WebApplication1
{
	public class Security
	{
		public Security()
		{
		}
	}
}

I’ll throw a bit more code into this file:

using System;
using System.Web;
namespace WebApplication1
{
	public class Security
	{
		public bool IsLoggedIn;
		public Security()
		{
			CheckSession();
		}
		private void CheckSession()
		{
			if (HttpContext.Current.Session["loggedin"] != null && HttpContext.Current.Session["loggedin"] == "true")
			{
				IsLoggedIn = true;
			}
			else
			{
				IsLoggedIn = false;
			}
		}
	}
}

Pretty simple so far. The only new thing is the use of HttpContext.Current.Session rather than just Session, that’s because HttpContext.Current is implicit in an .aspx web page, but not in a standalone class.

In our Default.aspx.cs code-behind file we write:

protected void Page_Load(object sender, EventArgs e)
{
	Security security = new Security();
	if (security.IsLoggedIn)
	{
		Title.Text = "Welcome back, you are logged in";
	}
	else
	{
		Title.Text = "You are not logged in";
	}
}

Which instantiates a new instance of the Security class names "security". Running the application shows this:

Not logged in

As you’re familiar with OOP you can see how this can be used to build large-scale web applications. The only other thing to say about custom classes is how to make them static. Here’s the code for a static class:

using System;
using System.Web;
namespace WebApplication1
{
	public static class Security
	{
		public static bool IsLoggedIn;
		public static void CheckSession()
		{
			if (HttpContext.Current.Session["loggedin"] != null && HttpContext.Current.Session["loggedin"] == "true")
			{
				IsLoggedIn = true;
			}
			else
			{
				IsLoggedIn = false;
			}
		}
	}
}

You can see there’s no default method, as this class is never instantiated. I’ve also added the "static" keyword to the property and method, and I’ve made the CheckSession() method public. To use this static class we would write:

protected void Page_Load(object sender, EventArgs e)
{
	Security.CheckSession();
	if (Security.IsLoggedIn)
	{
		Title.Text = "Welcome back, you are logged in";
	}
	else
	{
		Title.Text = "You are not logged in";
	}
}

Pretty simple, really. As you’re fully aware of the advantages that OOP can give you for abstraction, encapsulation and inheritance you’ll see how powerful this is. But if we’re going to use objects, we really need some serious data to model in our objects. We need a database.

Databases, Data Sources and Data Binding

ASP.NET works really well with databases, but works the best with Microsoft SQL Server (not surprisingly). Even if your ASP.NET application is running on a Linux box, you can still connect to SQL Server on a Windows server to use as a datastore. I’ll demonstrate that below, but as I’m writing this tutorial in Linux I will also demonstrate the use of MySQL as an ASP.NET database. To use MySQL you’ll need the ADO.NET driver for MySQLthis excellent article helped me a lot.

Database configuration

The first thing to do is configure how to connect to our database server. You can do this in web.config, add this code inside the "configuration" section (the MySQL and SQL Server code should be pretty obvious). Note that these are standard connection strings.

<connectionStrings>
    <add name="MySQL" connectionString="Server=mysqlserver;Database=aspnetdb1;User ID=root;Password=mypassword;Pooling=false"/>
    <add name="SQLServer" connectionString="Server=sqlserver;Database=aspnetdb1;User ID=sa;Password=myPassword;"/>
</connectionStrings>

I’ve also created a table called "users" with this code (this is for MySQL, minor edits will make it work in most other database systems):

CREATE TABLE users (
  id int  NOT NULL AUTO_INCREMENT,
  username varchar(50)  NOT NULL,
  password varchar(32)  NOT NULL,
  email varchar(255)  NOT NULL,
  PRIMARY KEY (id)
);

To access your connection string you can use the ConfigurationManager class which we used in part 1 of the tutorial to access global configuration settings. Here’s the code:

string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;

Connecting and running a simple query

So we’re now ready to connect to our database and run a query. First, insert a couple of rows into the " users" table so we have something to query:

insert into users
(username, password, email)
values
('User 1', 'user1password', '[email protected]')

We then need to ensure we reference the right assemblies. For MySQL make sure you have this at the top of your code-behind file:

using System.Data;
using MySql.Data.MySqlClient;

Amd for SQL Server use this:

using System.Data;
using System.Data.SqlClient;

A quick note about connecting to MySQL in Linux. I had a bit of trouble making my application compile when I first tried this. I did various searches but found no answer that worked for me. The error I got was "The type or namespace name `MySqlConnection’ could not be found." which looked like the MySQL Connector wasn’t installed properly. The fix (for me) was to manually add the reference by right-clicking the References folder in my application and going to "Edit references". I then found the MySQL.Data.dll file in the .Net Assembly tab and referenced it. I also had to then manually reference the System.Data and System.Configuration assemblies from the Packages tab.

MonoDevelop references

Hopefully you won’t need to jump through these hoops.

We now open a connection to our database like this for MySQL:

protected void Page_Load(object sender, EventArgs e)
{
	// get the connection string
	string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
	// create a new MySQL connection
	MySqlConnection dbcon;
	using (dbcon = new MySqlConnection(conn))
	{
		// open the connection
		dbcon.Open();
		// create the query
		string query = "SELECT username, email FROM users";
		// create a new adapter between the connection and query
		MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon);
		// create a new dataset to store the query results
		DataSet ds = new DataSet();
		// fill the dataset with the results from the adapter,
		// the name of the dataset is "result"
		adapter.Fill(ds, "result");

	}
}

And this for SQL Server:

protected void Page_Load(object sender, EventArgs e)
{
	// get the connection string
	string conn = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
	// create a new SQL Server connection
	SqlConnection dbcon;
	using (dbcon = new SqlConnection(conn))
	{
		// open the connection
		dbcon.Open();
		// create the query
		string query = "SELECT username, email FROM users";
		// create a new adapter between the connection and query
		SqlDataAdapter adapter = new SqlDataAdapter(query, dbcon);
		// create a new dataset to store the query results
		DataSet ds = new DataSet();
		// fill the dataset with the results from the adapter,
		// the name of the dataset is "result"
		adapter.Fill(ds, "result");

	}
}

See, pretty easy, and not a million miles away from the equivalent PHP code. There are a couple of bits in here I’ll explain in some more depth. Firstly the using statement:

using (something here) { ... }

The object you set up in the brackets is automatically destroyed when your code leaves the end curly brace "}". This is a really useful structure to know about, so read all about it here.

Secondly the DataSet. In the code above the results from the database query are fed into a DataSet, which is an object containing one or more tables, each table containing rows and columns. That means you can do useful things like:

DataSet ds = new DataSet();
// we put some data from the database in the DataSet here...
// get the number of tables
int tables = ds.Tables.Count;
// get the first table
DataTable dt = ds.Tables[0];
// get the number of rows in the first table
int rows = ds.Tables[0].Rows.Count;

And there are many other goodies in the DataSet class. You can also loop rows, just like you do in PHP, like this:

for (int x = 0; x < ds.Tables[0].Rows.Count; x++)
{
	Response.Write(ds.Tables[0].Rows[x]["fieldname"].ToString() + <br />);
}

But there’s a much better way to display simple loops, and that’s using the Repeater control.

Using repeaters and databinding

First a confession. There are large ASP.NET applications I’ve written that use no ASP.NET controls except the Literal (which we looked at above) and the Repeater. The Repeater control allows you to "bind" data, for example from a DataSet, and display it in a looped manner. Firstly we need to add something to our database code above:

protected void Page_Load(object sender, EventArgs e)
{
	// get the connection string
	string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
	// create a new MySQL connection
	MySqlConnection dbcon;
	using (dbcon = new MySqlConnection(conn))
	{
		// open the connection
		dbcon.Open();
		// create the query
		string query = "SELECT username, email FROM users";
		// create a new adapter between the connection and query
		MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon);
		// create a new dataset to store the query results
		DataSet ds = new DataSet();
		// fill the dataset with the results from the adapter,
		// the name of the dataset is "result"
		adapter.Fill(ds, "result");

		// below is the new code...

		// set the DataSource of the repeater
		myRepeater.DataSource = ds;
		// bind the data
		myRepeater.DataBind();

	}
}

And in the .aspx page we put:

<asp:Repeater id="myRepeater" runat="server">
<HeaderTemplate>
<table>
	<tr>
		<th>Username</th>
		<th>Email</th>
	</tr>
</HeaderTemplate>
<ItemTemplate>
	<tr>
		<td><%# Eval("username") %></td>
		<td><%# Eval("email") %></td>
	</tr>
</ItemTemplate>
<AlternatingItemTemplate>
	<tr class="alt">
		<td><%# Eval("username") %></td>
		<td><%# Eval("email") %></td>
	</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

You can see what happens here. When the data is bound to the Repeater control the HeaderTemplate section is displayed. Then each row is displayed in the ItemTemplate and AlternatingItemTemplate sections (the names should give you a clue how they are displayed). Then finally the FooterTemplate section is displayed. Using this simple control gives you an easy way to display repeating data, with complete control over the resulting HTML – just like you would do in PHP. Here’s the results (with some CSS for styling):

A simple example of a Repeater control

As a Repeater will throw an Exception if an empty DataSet is bound to it, you need to check there is data to be bound first. A simple if statement will work, checking if there are tables in the DataSet and if the first table has rows:

if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
	myRepeater.DataSource = ds;
	myRepeater.DataBind();
}

I think you’ll agree that having a control which sets templating for repeating data as easily as that is a massive help to the developer. One thing to note with the Repeater control – if you bind a DataSet to it by default the first table is used. If you’re using stored procedures instead of inline SQL to run commands against your database you can return multiple tables, meaning you can load several sets of data for use in a page at once. In that case you’d use code like this (to bind the second table in the DataSet to the Repeater):

myRepeater.DataSource = ds.Tables[1];
myRepeater.DataBind();

Creating a data access class

Let’s pull the last couple of sections together and create a data access class that will simplify connecting to and running commands on your database. This code is for MySQL, but as you’ve seen the code for SQL Server is very similar. Create a new empty class called "DB" and paste this into the new file:

using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

namespace WebApplication1
{
	public class DB
	{
		private string ConnectionString;
		public DB()
		{
			// get the connection string
			this.ConnectionString = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
		}
		public DataSet Select(string query)
		{
			MySqlConnection dbcon;
			using (dbcon = new MySqlConnection(this.ConnectionString))
			{
				// open the connection
				dbcon.Open();
				// create a new adapter between the connection and query
				MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon);
				// create a new dataset to store the query results
				DataSet ds = new DataSet();
				// fill the dataset with the results from the adapter,
				adapter.Fill(ds, "result");
				// return the dataset
				return ds;
			}
		}
		public bool Execute(string query)
		{
			MySqlConnection dbcon;
			using (dbcon = new MySqlConnection(this.ConnectionString))
			{
				// create a new SQL command on thie connection
				MySqlCommand command = new MySqlCommand(query, dbcon);
				// open the connection
				dbcon.Open();
				// execute the query and return the number of affected rows
				int affectedrows = command.ExecuteNonQuery();
				// there were no rows affected - the command failed
				if (affectedrows == 0)
				{
					return false;
				// the command affected at least one row
				} else {
					return true;
				}
			}
		}
	}
}

To use this in your code-behind file you’d put:

DB db = new DB();
DataSet ds = db.Select("SELECT username, email FROM users");
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
	myRepeater.DataSource = ds;
	myRepeater.DataBind();
}

This data access class introduces you to a new style of database connection syntax using the MySqlCommand class (SqlCommand for SQL Server) and the ExecuteNonQuery method. As the code says, the ExecuteNonQuery method executes a query and returns the number of affected rows. Very useful for INSERT, UPDATE and DELETE commands.

Those of you with a good knowledge of WordPress will see how this class is similar to the $wpdb global class in WP which offers methods like $wpdb->get_results("select * from table"); and $wpdb->query("delete * from table");. It would be easy for you to extend this data access class to have more useful properties and methods for your applications.

User Controls

So far we’ve used just two ASP.NET controls – Literal and Repeater – in honour of our aim to keep full control of the output HTML. But sometimes it’s useful to encapsulate functionality for your own controls. ASP.NET allows you to create user controls with properties and methods all your own. These user controls can be thought of as discrete blocks of HTML that can be used inside a .aspx page, just like you’d include a separate file in a .php file.

We’re going to create a very simple control that displays a truncated link. Firstly add a new file of type "User control with code-behind file" and call it "ShortLink".

Adding a new user control

You may notice the new file has an extension of .ascx, this is the extension for user controls. Open the .ascx file and you’ll see this:

<%@ Control Language="C#" Inherits="WebApplication1.ShortLink" %>

Open the code-behind file (MyControl.ascx.cs) and you’ll see this:

using System;
using System.Web;
using System.Web.UI;

namespace WebApplication1
{
	public partial class MyControl : System.Web.UI.UserControl
	{
	}
}

Now we’re ready to create our user control. Paste this code into the .ascx.cs (code-behind) file (I won’t explain this code, it’s simple enough):

using System;
using System.Web;
using System.Web.UI;
namespace WebApplication1
{
	public partial class ShortLink : System.Web.UI.UserControl
	{
		public string Link;
		protected void Page_Load(object sender, EventArgs e)
		{
			// set the href attribute
			theLink.Attributes["href"] = Link;

			// declare the short link, replacing protocols
			string shortlink = Link.Replace("http://", "").Replace("https://", "");

			// if the link is longer than 15 characters
			if (shortlink.Length > 15)
			{
				// show the first 6 and last 6 characters
				theLink.InnerHtml = shortlink.Substring(0, 6) + "..." + shortlink.Substring(shortlink.Length-6);
			}
			else
			{
				// show the full link
				theLink.InnerHtml = shortlink;
			}

		}
	}
}

Yes, user controls use the same Page_Load event handler that normal .aspx pages use. Now open the .ascx file and paste this into it:

<%@ Control Language="C#" Inherits="WebApplication1.ShortLink" %>
<a href="" id="theLink" runat="server"></a>

Here you can see instead of a Page declaration we have a Control declaration, but the same Inherits property to bind it to the code-behind file. We also have a standard <a> element with the runat="server" property to make it a server-side control.

To use this control in your page simply register a tag prefix (this can be anything) at the top of the page like this:

<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %>
<%@ Register TagPrefix="My" TagName="ShortLink" Src="ShortLink.ascx" %>

Then use the control wherever you want to. To demonstrate this control I’m using two instances of it:

<p><My:ShortLink id="Link1" Link="http://www.google.com" Runat="server"></My:ShortLink></p>
<p><My:ShortLink id="Link2" Link="http://www.google.com/search?q=asp.net+for+php+developers" Runat="server"></My:ShortLink></p>

The TagPrefix property is the first part of the control tag and the TagName the second part, separated by ":" – My:ShortLink. And this is the result:

A simple user control

Here you can see that the public string property I declared in my ShortCode user control class (public string Link;) can be set in a Link property of the control. You can have any number of properties and they can be of any type. You can only set string types in the control tag itself (i.e Link="http://www.google.com"), as you can set the properties programatically from your code-behind file (like Link1.DatasetProperty = new DataSet();).

There’s one bit of code here which needs a little more explanation.

Using a custom tag prefix

Your user controls need to have their own tag prefix. In our example above this is "My", but of course it can be any simple string. In the example above the tag prefix was registered, so ASP.NET knew what to do when it encountered it, using a declaration at the top of the page:

<%@ Register TagPrefix="My" TagName="ShortLink" Src="ShortLink.ascx" %>

However it’s possible to register your tag prefixes in your web.config file, so you don’t have to do it on every page (as explained by Scott Guthrie – that’s one blog you’ll want to follow). Here’s how, but before you rush in watch out for the error I got:

Parser Error Message: The page '/Default.aspx' cannot use the user control '/ShortLink.ascx', because it is registered in web.config and lives in the same directory as the page.

So put your user controls in a subfolder, for example "Controls".

<?xml version="1.0"?>
<configuration>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="My" src="~/Controls/ShortLink.ascx" tagName="ShortLink"/>
      </controls>
    </pages>
  </system.web>
</configuration>

You’ll now want to put user controls everywhere. And the best thing about user controls is, because they are just like pages (without <html>, <head> and <body> tags) you can put anything you like in them. In fact it would be possible to write an entire application in user controls, including the relevent controls in your page depending on some parameters passed to it. Amazing.

Compiling and Deploying

As mentioned in part 1 of the tutorial, C# is a compiled language. Rather than PHP, which is compiled into language the computer can understand at runtime, C# is pre-compiled (or sometimes compiled on first run) and saved in assemblies for the computer to process.

This means that C# is faster (yes, it’s true, sorry), and that you can catch a lot of errors in your code *before* you try to run it. You’ve already seen that happening when we discussed errors above. However, it means you can’t just drop your ASP.NET application on a server and expect it to run. It also means you can’t do live hacking of your code-behind files in a running application. Deployment needs to be approached a little more methodically than in PHP.

There are several other articles which do a much better job at explaining this than I would so I’ll just link to them.

Next Steps

Hopefully between part 1 and this tutorial, you now have a much better idea of what ASP.NET is, and the advantages it can provide for developers. For further reading, you can check out some of my favourite places:

Finally, good luck! It’s been a hard climb for me, as a PHP guy for many years, to get to grips with ASP.NET. However I’ve found many good things in the framework, and have come to appreciate the power of the C# language – without losing my love for PHP. I hope that you can do the same.



Quick Tip: Easy Sequential Animations in jQuery

Quick Tip: Easy Sequential Animations in jQuery

In this video quick tip, I’ll demonstrate an easy way to allow for sequential animations of an infinite number of elements. I originally learned this technique from Dave Methvin, but don’t think that many people are aware of this neat little trick.


The Goal

We want to filter through an infinite number of elements on a page, matching some selector, and then make them sequentially fade out.

The HTML

<body>
  <p>Watch</p>
  <p>Me</p>
  <p>Disappear</p>
</body>

The jQuery

var paras = $('p'),
    i = 0;

// If using jQuery 1.4, you don't need to do || [].
(function() {
  $(paras[i++] || []).fadeOut('slow', arguments.callee);
})();

We begin by “caching” all of the paragraphs on the page, wrapped in the jQuery object (var paras). We also create an iterator variable – i. This iterator will allows us to target each new paragraph element, without knowing the specific length of the paras object ahead of time.

Within the self-invoking anonymous function, we get the first paragraph on the page with “paras[i]” … But we want to increment i by one for each iteration. This way, the next time the selection is called, it’ll be referring to the next element in the wrapped set. So, we must be sure to write paras[i++]. Then, it’s a simple matter of calling fadeout, and passing arguments.callee as the callback function, to allow for recursion. This will be equal to the function it’s contained in; so we’re essentially saying “rinse and repeat!”

alert(arguments.callee); // alerts the following

 (function() {
  $(paras[i++] || []).fadeOut('slow', arguments.callee);
})();

Note

If, for some reason, you’re using jQuery 1.3 or older, you need to specify what should happen when paras[i] is equal to an element that doesn’t exist. In older versions of jQuery, it returns an error, “undefined.” To compensate, we pass $(paras[i++] || []) to specify that, if the element doesn’t exist, we instead wrap an empty array, to avoid any errors.

It should be noted that, as of jQuery 1.4, this is unnecessary, as jQuery will return the jQuery object instead.



Integrating PHP and jQuery: New Plus Tutorial

Integrating PHP and jQuery: New Plus Tutorial

So you can work with PHP, and have a basic understanding of jQuery, but you haven’t yet figured out how to combine the two into your projects? If so, we’ve got you covered today! In this Plus tutorial, you’ll learn how to take advantage of PHP’s MySQL improved and prepared statements to query a database, how to request that returned data with jQuery, and then how to filter through the returned items and display them on the page, adding a touch of animations. If this sounds interesting, give back to Nettuts+, and become a Plus member to watch this helpful video tutorial!

In this screencast, you’ll learn how to:

  • Create a new database
  • Query that database with MySQL improved and prepared statements
  • Make AJAX requests with jQuery to retrieve the information that was pulled from the database
  • Filter through that returned information, and display it on the page
  • Add a bit of animation
  • Create singletons with JavaScript
  • Create private variables in JavaScript
  • Throw errors to allow for easier debugging

Join Tuts Plus

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service called “TUTSPLUS”. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!

  • Subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.



Make your MooTools Code Shorter, Faster, and Stronger

Make your MooTools Code Shorter, Faster, and Stronger

MooTools is one of the most flexible, modular, and well written JavaScript frameworks available. So many people use it but many of them don’t optimize their code. This post will provide you with fifteen simple tips for making your MooTools code shorter, faster, and stronger.

1. Create Your Own MooTools Build or Pull From Google AJAX Libraries

One of the great advantages to using MooTools is that it’s incredibly modular. What does that mean?
Almost nothing is required unless you need it. The advantage of MooTools’ modularity is that your
limited, custom MooTools build can keep your JavaScript load time short.

MooTools Core Builder

Want to create a custom MooTools build for your next project? Follow these steps:

  • Go to http://mootools.net/core (and/or http://mootools.net/more if you’d like additional plugins)
  • Select the plugins of your choosing. Don’t worry about accounting for dependencies — the plugin builder does that for you!
  • Select the compression option of your choosing — the YUI Compressor will provide the you with the smallest possible build of MooTools

That’s it! Sometimes, however, your project requires the entire MooTools Core library. In that case, your website can save itself thousands
of requests per day by using the Google AJAX Libraries complete build of MooTools. You may do this two ways:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"></script>

This first method simply includes MooTools into the page per normal. The second method allows more functionality and performance:

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("mootools", "1.2.4"); //older versions also available
</script>

What’s great about using the Google AJAX Libraries API is that if another website uses the AJAX Library API, that version of MooTools is already cached
within their browser and the site will load faster!

2. Use jQuery and MooTools Together

While it’s best to stick to one library in a given page to avoid a bunch of overhead, sometimes you can’t avoid needing multiple frameworks.
Luckily MooTools can coexist with any non-prototype-based JavaScript frameworks. Here’s how you can use jQuery and MooTools in the same page:

<!-- jquery gets the "$" method -->
<script type="text/javascript" src="jquery-1.4.js" />
<!-- mootools doesn't steal the "$" method; instead, document.id will be used -->
<script type="text/javascript" src="mootools.js" />
<!-- lets use them -->
<script type="text/javascript">
//with jquery, grab all links, make then red
$('a').css('color','red');
//with mootools, get the content div, set it's background color to pink
document.id('content').setStyle('background','pink');
//with mootools, get the content div, set it's background color to pink
//this time, we'll give mootools the "$" method
(function($) {
	$('content').setStyle('background','pink');
})(document.id);
</script>

Thanks to MooTools’ Dollar Safe Mode, MooTools no longer assumes the “$” method if it’s already taken!

3. Save Elements and Element Collections

Developers often need to collect one element or a collection of elements. For example, you may need to grab all A elements within the page, change their color, and create tooltips from them.

//grab links, change color */
$$('#footer a').setStyle('color','#f00');
//make links tooltips
var tippers = new Tips($$('#footer a'));

The code above is grossly inefficient. Why query the DOM twice (with $$) if you can collect all of the elements once? Let’s make this more efficient:

//"save" links into a variable
var links = $$('#footer a');
//grab links, change color */
links.setStyle('color','#f00');
//make links tooltips
var tippers = new Tips(links);

You could make this even shorter, but it’s not as readable:

var tippers = new Tips($$('#footer a').setStyle('color','#f00'));

Readability is important, so I wouldn’t recommend coding this way if you work with a team.

4. Use Element Methods on Element Collections

Cycling through an array of elements is not unique to any JavaScript framework:

//for every link...
$$('a').each(function(a) {
	//add link nudging to the element
	a.addEvents({
		mouseenter: function() { //animate to the right
			if(!a.retrieve('oPad')) { a.store('oPad',a.getStyle('padding-left')); }
			a.tween('padding-left',30);
		},
		mouseleave: function() { //animate back to the left
			a.tween('padding-left',a.retrieve('oPad'));
		}
	});
});

What many developers aren’t aware that Element collections have the same methods as Elements,
so there’s no need to cycle through them — simply apply the desired functionality to the collection:

$$('a').addEvents({
	mouseenter: function() { //animate to the right
		if(!this.retrieve('oPad')) { this.store('oPad',this.getStyle('padding-left')); }
		this.tween('padding-left',30);
	},
	mouseleave: function() { //animate back to the left
		this.tween('padding-left',this.retrieve('oPad'));
	}
});

Note that the “this” keyword is used to reference the “current” element within the collection, not the collection itself.

5. Use MooTools Alias

MooTools’ “alias” method allows you to rename or alias an existing method. Take the following snippet of code which is currently in the MooTools Core source:

Array.alias('forEach', 'each');

The above code lets you call the “each” method instead of “forEach”. Using “each” is more readable, a quiet standard between most JavaScript frameworks, and
it even saves you a few bytes in your code. If you prefer to give MooTools’ Native or Class methods a custom name, feel free to!

For example, the Element Class’ method for removing an Element form the DOM is:

$('myElement').dispose();

Suppose your web app is about a given topic and you’d like to stay within that terminology for your code. Here are a few examples:

Element.alias('dispose','can'); //career site?
Element.alias('dispose','shank'); //prison site?

Whatever your reasons are for calling a method by a different name, just don’t be afraid to do so!

6. Create Custom Pseudo Selectors

Accessing a collection of Elements in the DOM is a core responsibility of any JavaScript framework. Unfortunately it can also be taxing and
the pseudo selectors you want aren’t always available. Luckily MooTools allows you to easily implement your own pseudo selectors! Let’s
create a pseudo selector named “disabled” that returns an element if it’s disabled.

//grab disabled elements
Selectors.Pseudo.disabled = function() {
	return this.disabled;
}

//how you use it
var disabledInputs = $$('input:disabled');

Simply add your selector to the Selectors.Pseudo object. If the new pseudo’s function returns “true”, the element is a match and will be returned.

Defining you own pseudo selectors is a great way to take control of your selectors!

7. Implement Methods on Existing Objects

MooTools’ philosophy is that it’s acceptable, even encouraged, to modify Native (String, Function, Number, etc.) prototypes when needed.
Implementing new methods on these Natives will empower them even more. Let’s create a String method that will turn any string of text into
“tweet” format (add links for @reply’s, links, etc.):

String.implement({
	toTweet: function() {
		 return this.replace(/(https?:\/\/\S+)/gi,'<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>');
	}
});

Now you can call “toTweet” on any string and you’ll get the string back as a “tweet”. Here are a few examples:

//set an element's html to a tweet value
var el = $('myElement');
el.set('html',el.get('html').toTweet()); //sets the element's html to a linked, tweet value.

//alert the tweeted value
alert('Yo @NetTuts, check out my #MooTools website: http://davidwalsh.name'.toTweet());
//alerts:  Yo <a href="http://twitter.com/nettuts">@NetTuts</a>, check out my <a href="http://search.twitter.com/search?q=%23MooTools">MooTools</a> website: <a href="http://davidwalsh.name">http://davidwalsh.name</a>

Implementing custom methods on Objects strengthens every existing and future instance of that object.

8. Extend Existing Classes

MooTools’ OOP philosophy allows for a super-powerful inheritance model. Extending existing classes
allows you to avoid repeating code, empower existing objects, and leverage existing functionality.
MooTools Core, More, and your custom classes extend existing functionality. Consider the Request class:

var Request = new Class({

	Implements: [Chain, Events, Options],

	options: {/*
		onRequest: $empty,
		onComplete: $empty,
		onCancel: $empty,
		onSuccess: $empty,
		onFailure: $empty,
		onException: $empty,*/
		url: '',
		data: '',
		headers: {
			'X-Requested-With': 'XMLHttpRequest',
			'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
		},
		async: true,
		format: false,
		method: 'post',
		link: 'ignore',
		isSuccess: null,
		emulation: true,
		urlEncoded: true,
		encoding: 'utf-8',
		evalScripts: false,
		evalResponse: false,
		noCache: false
	},

	initialize: function(options){
		this.xhr = new Browser.Request();
		this.setOptions(options);
		this.options.isSuccess = this.options.isSuccess || this.isSuccess;
		this.headers = new Hash(this.options.headers);
	},

	onStateChange: function(){
		if (this.xhr.readyState != 4 || !this.running) return;
		this.running = false;
		this.status = 0;
		$try(function(){
			this.status = this.xhr.status;
		}.bind(this));
		this.xhr.onreadystatechange = $empty;
		if (this.options.isSuccess.call(this, this.status)){
			this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML};
			this.success(this.response.text, this.response.xml);
		} else {
			this.response = {text: null, xml: null};
			this.failure();
		}
	},

	isSuccess: function(){
		return ((this.status >= 200) && (this.status < 300));
	},

	processScripts: function(text){
		if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
		return text.stripScripts(this.options.evalScripts);
	},

	success: function(text, xml){
		this.onSuccess(this.processScripts(text), xml);
	},

	onSuccess: function(){
		this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
	},

	failure: function(){
		this.onFailure();
	},

	onFailure: function(){
		this.fireEvent('complete').fireEvent('failure', this.xhr);
	},

	setHeader: function(name, value){
		this.headers.set(name, value);
		return this;
	},

	getHeader: function(name){
		return $try(function(){
			return this.xhr.getResponseHeader(name);
		}.bind(this));
	},

	check: function(){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
		}
		return false;
	},

	send: function(options){
		if (!this.check(options)) return this;
		this.running = true;

		var type = $type(options);
		if (type == 'string' || type == 'element') options = {data: options};

		var old = this.options;
		options = $extend({data: old.data, url: old.url, method: old.method}, options);
		var data = options.data, url = String(options.url), method = options.method.toLowerCase();

		switch ($type(data)){
			case 'element': data = document.id(data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(data);
		}

		if (this.options.format){
			var format = 'format=' + this.options.format;
			data = (data) ? format + '&' + data : format;
		}

		if (this.options.emulation && !['get', 'post'].contains(method)){
			var _method = '_method=' + method;
			data = (data) ? _method + '&' + data : _method;
			method = 'post';
		}

		if (this.options.urlEncoded && method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}

		if (this.options.noCache){
			var noCache = 'noCache=' + new Date().getTime();
			data = (data) ? noCache + '&' + data : noCache;
		}

		var trimPosition = url.lastIndexOf('/');
		if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);

		if (data && method == 'get'){
			url = url + (url.contains('?') ? '&' : '?') + data;
			data = null;
		}

		this.xhr.open(method.toUpperCase(), url, this.options.async);

		this.xhr.onreadystatechange = this.onStateChange.bind(this);

		this.headers.each(function(value, key){
			try {
				this.xhr.setRequestHeader(key, value);
			} catch (e){
				this.fireEvent('exception', [key, value]);
			}
		}, this);

		this.fireEvent('request');
		this.xhr.send(data);
		if (!this.options.async) this.onStateChange();
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.xhr.abort();
		this.xhr.onreadystatechange = $empty;
		this.xhr = new Browser.Request();
		this.fireEvent('cancel');
		return this;
	}

});

Then consider Request.JSONP, which extends Request:

Request.JSON = new Class({

	Extends: Request,

	options: {
		secure: true
	},

	initialize: function(options){
		this.parent(options);
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);
		this.onSuccess(this.response.json, text);
	}

});

You see how small the Request.JSONP class is? By adding “Extends: Request”, the Request.JSONP class gets all
of the Request Class’ methods. Essentially, this small snippet of code becomes a powerhouse because it extends
Request. You can even add extensions to extensions. Now consider Request.JSONP and then Scott Kyle’s Request.Twitter
class:

//Request.JSONP
/*
---

script: Request.JSONP.js

description: Defines Request.JSONP, a class for cross domain JavaScript via script injection.

license: MIT-style license

authors:
- Aaron Newton
- Guillermo Rauch

requires:
- core:1.2.4/Element
- core:1.2.4/Request
- /Log

provides: [Request.JSONP]

...
*/

Request.JSONP = new Class({

	Implements: [Chain, Events, Options, Log],

	options: {/*
		onRetry: $empty(intRetries),
		onRequest: $empty(scriptElement),
		onComplete: $empty(data),
		onSuccess: $empty(data),
		onCancel: $empty(),
		log: false,
		*/
		url: '',
		data: {},
		retries: 0,
		timeout: 0,
		link: 'ignore',
		callbackKey: 'callback',
		injectScript: document.head
	},

	initialize: function(options){
		this.setOptions(options);
		if (this.options.log) this.enableLog();
		this.running = false;
		this.requests = 0;
		this.triesRemaining = [];
	},

	check: function(){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
		}
		return false;
	},

	send: function(options){
		if (!$chk(arguments[1]) && !this.check(options)) return this;

		var type = $type(options),
				old = this.options,
				index = $chk(arguments[1]) ? arguments[1] : this.requests++;
		if (type == 'string' || type == 'element') options = {data: options};

		options = $extend({data: old.data, url: old.url}, options);

		if (!$chk(this.triesRemaining[index])) this.triesRemaining[index] = this.options.retries;
		var remaining = this.triesRemaining[index];

		(function(){
			var script = this.getScript(options);
			this.log('JSONP retrieving script with url: ' + script.get('src'));
			this.fireEvent('request', script);
			this.running = true;

			(function(){
				if (remaining){
					this.triesRemaining[index] = remaining - 1;
					if (script){
						script.destroy();
						this.send(options, index).fireEvent('retry', this.triesRemaining[index]);
					}
				} else if(script && this.options.timeout){
					script.destroy();
					this.cancel().fireEvent('failure');
				}
			}).delay(this.options.timeout, this);
		}).delay(Browser.Engine.trident ? 50 : 0, this);
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.fireEvent('cancel');
		return this;
	},

	getScript: function(options){
		var index = Request.JSONP.counter,
				data;
		Request.JSONP.counter++;

		switch ($type(options.data)){
			case 'element': data = document.id(options.data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(options.data);
		}

		var src = options.url +
			 (options.url.test('\\?') ? '&' :'?') +
			 (options.callbackKey || this.options.callbackKey) +
			 '=Request.JSONP.request_map.request_'+ index +
			 (data ? '&' + data : '');
		if (src.length > 2083) this.log('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');

		var script = new Element('script', {type: 'text/javascript', src: src});
		Request.JSONP.request_map['request_' + index] = function(){ this.success(arguments, script); }.bind(this);
		return script.inject(this.options.injectScript);
	},

	success: function(args, script){
		if (script) script.destroy();
		this.running = false;
		this.log('JSONP successfully retrieved: ', args);
		this.fireEvent('complete', args).fireEvent('success', args).callChain();
	}

});

Request.JSONP.counter = 0;
Request.JSONP.request_map = {};

…and now Request.Twitter:

Request.Twitter = new Class({

	Extends: Request.JSONP,

	options: {
	  linkify: true,
	  url: 'http://twitter.com/statuses/user_timeline/{term}.json',
	  data: {
	    count: 5
	  }
	},

	initialize: function(term, options){
	  this.parent(options);
	  this.options.url = this.options.url.substitute({term: term});
	},

	success: function(data, script){
	  if (this.options.linkify) data.each(function(tweet){
	    tweet.text = this.linkify(tweet.text);
	  }, this);

	  // keep subsequent calls newer
	  if (data[0]) this.options.data.since_id = data[0].id;

	  this.parent(data, script);
	},

	linkify: function(text){
	  // modified from TwitterGitter by David Walsh (davidwalsh.name)
	  // courtesy of Jeremy Parrish (rrish.org)
	  return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
	             .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
	             .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
	}

});

You see how a waterfall effect of extending objects can make the smallest of classes an absolute beast of a class?
Experiment with MooTools’ inheritance model and don’t repeat code!

9. Create Custom Events

I’ve already explained how flexible the MooTools selector engine is, the class system is, and how modular the framework is.
Why would you expect anything different from MooTools’ event system? Creating custom events within MooTools is as simple
as it gets. Here’s a basic outline of your MooTools custom event:

Element.Events.altClick = {
	base: 'click', //the "base" event
	condition: function(event) {
		return event.alt; // alt key?
	},
	onAdd: function() {
		//do something when the event is added
	},
	onRemove: function() {
		//do something when the event is removed
	}
};

Here’s a great example of a custom event — listening for “alt” and “click” at the same time:

//alt click
Element.Events.altClick = {
	base: 'click',
	condition: function(event) {
		return event.alt; // alt key?
	}
};

//usage
$(document.body).addEvent('altClick',function() {
	alert('You alt-clicked me!');
});

Or you can simply define a custom event so that a specific function executes any time that type of event is assigned.
In my next example, any time a click event is assigned to an element, that element’s cursor will be automatically changed
to the “pointer” cursor.

/* update cursor on add/remove click event */
Element.Events.click = {
	base:'click',
	onAdd: function() {
		if(this.setStyle) {
			this.store('original-cursor',this.getStyle('cursor'));
			this.setStyle('cursor','pointer');
		}
	},
	onRemove: function() {
		if(this.setStyle) {
			this.setStyle('cursor',this.retrieve('original-cursor'));
		}
	}
};

You’ll notice that if the click event is removed, the original cursor will be restored.

10. jQuery-Style Events

While the MooTools event sytax is different from jQuery’s, it doesn’t have to be! With a minimal amount of
javascript you can make MooTools’ event syntax reflect jQuery’s.

MooTools holds all of its events in the Element.NativeElements object:

Element.NativeEvents = {
	click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
	mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
	mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
	keydown: 2, keypress: 2, keyup: 2, //keyboard
	focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements
	load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
	error: 1, abort: 1, scroll: 1 //misc
};

Essentially all you need to do is cycle through each element type and implement a method on the Element class, named like the event type,
that simulates what addEvent does:

//hash the element.natives so you can do stuff with it
var hash = new Hash(Element.NativeEvents);
//remove items that need to be replaced, add their replacements
hash.erase('mouseover').erase('mouseout').erase('DOMMouseScroll');
hash.include('mouseenter',1).include('mouseleave',1);
//initialize this
var eventHash = new Hash({});
//for every event type, add to the hash
hash.getKeys().each(function(event){
	eventHash[event] = function(fn) {
		this.addEvent(event,fn);
		return this;
	};
});
//make it happen
Element.implement(eventHash);

Now you can listen for events like:

$('myElement').click(function() {
	//do stuff
});

11. Add Events During Element Creation

If you have experience coding with MooTools, at some point you’ve no doubt created an element and subsequently added events to it:

var myElement = new Element('a',{
	href: 'mypage.php',
	text: 'Click here!'
});

myElement.addEvent('click',function(e) {
	//stop the event
	if(e) e.stop();
	//do stuff
});

There’s nothing wrong with the above, per say, but you could just add those events during element creation:

var myElement = new Element('a',{
	href: 'mypage.php',
	text: 'Click here!',
	events: {
		click: function() {
			//stop the event
			if(e) e.stop();
			//do stuff
		}
	}
});

12. Implement Events Within Classes

Extending classes was discussed in tip #8 above. Now lets explore the *implement* functionality within MooTools classes.
What’s the difference? MooTools contributor Mark Obcena says it best in his article titled
Up The Moo Herd IV: There’s A Class For This:

MooTools has two built-in mutators: Extends and Implements. The Extends mutator takes the class name passed on to it and makes the new class inherit directly from it, while Implements takes the class (or classes) passed and adds their methods to the new class (or mixes them in—thus mixin).

With the difference between extending and implementing, lets get back to it. Implementing events within your MooTools classes
can make your classes much more flexible. Consider the following simple Overlay class:

var Overlay = new Class({

	Implements: [Options,Events],

	options:  {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.5,
		zIndex: 5000
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = document.id(container);
		this.overlay = new Element('div',{
			id: this.options.id,
			opacity: 0,
			styles: {
				position: 'absolute',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			},
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay,{
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				this.overlay.setStyles({
					width: '100%',
					height: this.container.getScrollSize().y
				});
			}.bind(this)
		});
	},
	open: function() {
		this.tween.start(this.options.opacity);
		return this;
	},
	close: function() {
		this.tween.start(0);
		return this;
	}
});

Sure the class does what it’s supposed to but it isn’t nearly as flexible it could be. Now lets implement
onClick, onClose, onHide, onOpen, and onShow events:

var Overlay = new Class({

	Implements: [Options,Events],  // EVENTS IMPLEMENTED HERE!

	options:  {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.5,
		zIndex: 5000/*,
		onClick: $empty,
		onClose: $empty,
		onHide: $empty,
		onOpen: $empty,
		onShow: $empty
		*/
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = document.id(container);
		this.overlay = new Element('div',{
			id: this.options.id,
			opacity: 0,
			styles: {
				position: 'absolute',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			},
			events: {
				click: function() {    // CLICK EVENT
					this.fireEvent('click');
				}.bind(this)
			}
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay,{
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				this.overlay.setStyles({
					width: '100%',
					height: this.container.getScrollSize().y
				});
			}.bind(this),
			onComplete: function() {
				this.fireEvent(this.overlay.get('opacity') == this.options.opacity ? 'show' : 'hide');  // SHOW OR HIDE EVENT
			}.bind(this)
		});
	},
	open: function() {
		this.fireEvent('open');  // OPEN EVENT
		this.tween.start(this.options.opacity);
		return this;
	},
	close: function() {
		this.fireEvent('close');  // CLOSE EVENT
		this.tween.start(0);
		return this;
	}
});

What’s great about adding events to a class is that events allow your to give more options and trigger functionality when
our class methods execute. In the above example, you can execute any functionality when the overlay opens, closes, shows, hides, or gets clicked.
Essentially you added two tiny snippets of code to the class:

Implements: [Events]

…and the following wherever you’d like an event to be signaled…

this.fireEvent('someEvent',[argument1, argument2]);

So how can you control these events when you create an instance of the class? Add them in the options like this:

var overlay = new Overlay({
	onClick: function() {
		this.hide();
	},
	onOpen: function() {
		alert('Thank you for opening!');
	}
});

You’d be hard pressed to find a class that wouldn’t benefit from implementing events!

13. Use Event Delegation

Event delegation is the process of adding an event to a parent for all of its children instead of assigning the
event to each individual child. The advantage of event delegation is that you may add child elements to the
parent element without needing to assign the event to that new element. If you choose to remove the event,
you need only remove it from one element.

So, instead of:

$$('a').addEvent('click',function() {
	//do stuff -- individually assigned
});

…you do this:

$('myContainer').addEvent('click:relay(a)',function() {
	//assigned to the parent of all A elements (in this case, #myContainer), to listen to A element click event
})/

Don’t let the “:relay()” pseudo-syntax fool you; Element.Delegation rewrites the event methods to accommodate for :relay.

14. Use Class.toElement

One hidden gem within MooTools’ Class is the Class.toElement method. Class.toElement plays a small role but can help you out
when it comes to accessing the primary element within a class, especially if you don’t know what that element is otherwise.
Implementing toElement on your class is easy:

var myClass = new Class({

	Implements: [Options],

	initialize: function(container,options) {
		this.container = $(container);
	},

	toElement: function() {
		return this.container;
	}
});

Once you have toElement defined, you can use your class just like an element:

var myInstance = new MyClass('myElement');
myInstance.setStyle('color','#f00').set('html','This is my element!');

Look at that — a class virtually manipulated by Element methods.

15. “return this” Within Methods For Chainability

So we’ve all seen how the JavaScript frameworks allow you to chain the hell out of methods. Chaining looks like this:

$('myElement').setStyles('color','#f00').set('html','Click Here').fade('out').addClass('cssClass').addEvent('click',function(e) {
	if(e) e.stop();
	alert('Clicked'!);
});

Holy chaining Batman! Want your classes to chain forever? No problem — all you need to do is return “this”:

var myClass = new Class({

	//options, initialize, implements, etc.

	doSomething: function() {
		//do a whole bunch of functionality here and...
		return this;
	},
	doAnotherThing: function() {
		//do a whole bunch of functionality here and...
		return this;
	},
	doYetAnotherThing: function() {
		//do a whole bunch of functionality here and...
		return this.
	}
});

Since you placed “return this” in each method, now you can do:

var klass = new myClass();
klass.doSomething().doAnotherThing().doYetAnotherThing();

Make sure to return “this” wherever it makes sense. Doing so can make your Class much easier to work with and your code will be shorter!

BONUS! 16. Use Fx Shortcuts on Elements

MooTools effects are unarguably the smoothest of any JavaScript framework. The Fx library also provides loads of control through numerous options.
Lets take a look at a basic Tween which fades an element to 50%:

var myTween = new Fx.Tween('myElement',{
	duration: 500,
	fps: 200,
	//a bunch of options here
});
//fade to 50%
$('myElement').addEvent('click',function() {
	myTween.start('opacity',0.5);
});

Did you know you didn’t need to type out all of this? You could use element shortcuts like:

$('myElement').fade(0.5); //fading: Fx.Tween
$('myElement').tween('width',300); //tweening: Fx.Tween
$('myElement').morph({
	width: 200,
	height: 300
}); //morph:  Fx.Morph

The above snippets, of course, rely on you wanting to use the default options. You can actually set custom options for these shortcut methods per element:

$('myElement').set('tween',{ duration:500, fps: 200 }).tween('width',300);

Save your self a few bytes by using Fx shortcuts!

MooTools FTW!

Hopefully I’ve given you some tips to improve your MooTools JavaScript code, making it shorter, faster, and stronger. Have some of your own tips to share?
Place them in the comments below!



How to Create a Better WordPress Options Panel

How to Create a Better WordPress Options Panel

Today, we’ll go through the entire process of creating an admin options panel for a WordPress theme. Then, we’ll take things a step further, as we implement jQuery to improve some of the functionality.

Tutorial Details

  • Program: WordPress
  • Version: 2.7, 2.8, 2.9 onwards
  • Difficulty: Intermediate
  • Estimated Completion Time: 1.5 hours
Final Product

WordPress is one of the most popular Content Management Software (CMS) systems out there. Whether it be for a client project or for selling themes on ThemeForest, WordPress is fast emerging as a CMS of choice for many web developers. It’s relatively easy to use, but can be made even simpler when you include an administration panel for users. Rather than having to open up the PHP template files and fiddling with the code, users can directly use the options panel to interact with your WordPress theme.

For example – if your theme has red, blue and green color schemes, and each has a corresponding CSS file, it would be far easier for a user to select their preferred color from a dropdown list. So today, let me guide you through the entire process of creating and enhancing a WordPress admin panel page inspired by Woo.

Step 1

Before we begin creating the admin panel, we need to have a theme, right? So download the source files provided with the tutorial. I’ve slightly modified the Classic WordPress theme. Place the ‘nettuts’ folder (I’ve named the theme ‘Nettuts’) in your wp-content/themes folder. You should see the following files:

  • functions.php (blank)
  • index.php
  • comments.php
  • footer.php
  • header.php
  • rtl.php
  • sidebar.php
  • style.css
  • screenshot.png
  • An images folder with two files

Most of our work is going to be done within functions.php file.

A theme can optionally use a functions file, which resides in the theme subdirectory and is named functions.php. This file basically acts like a plugin, and if it is present in the theme you are using, it is automatically loaded during WordPress initialization (both for admin pages and external pages).

Suggested uses for this file:

  • Define functions used in several template files of your theme
  • Set up an admin screen, giving users options for colors, styles, and other aspects of your theme

(From the WP Codex)

Step 2

Now that we’ve got our WordPress theme set up, go to Appearance>Themes, and activate the nettuts theme.

Activated? Ok, great. Now we have to think of a layout for our admin panel page. Here’s the structure I’ve decided upon:

<div class="wrap rm_wrap">
	<div class="rm_opts">
		<form method="post">
			<div class="rm_section">
				<div class="rm_title>
					<h3>Title</h3>
					<submit button>
				</div>
				<div class="rm_input rm_<select/textarea/text etc>">
					<input area>
					<description>
				</div>
			</div>

			/*Repeat the inputs for as many options as required. */
			/* use <div class="rm_section"> for each new section of inputs eg General, Home Page etc */
		</form>
	</div>
</div>

Let me explain all of that to you. The options set is going to be wrapped up into a div named “rm_wrap” and then “rm_opts” for the options. Then we start a form, with all the inputs within it. Each section of options(general Settings, Homepage settings, Blog settings etc) has a separate div with a class of “rm_section”. This div has a title (for the name) as well as several input divs within it. By using classes like <div class=”rm_input rm_select”>, we can style dropdowns, text inputs, and textareas differently.

Now, the most important thing is that the coding of this shouldn’t be done manually – we should use PHP’s flexibility as much as possible. That means efficiency: don’t code manually when you have loops for you!

Step 3

Begin by opening up functions.php in your favorite code editor (I use Notepad++). Enter the following code:

<?php

$themename = "Nettuts";
$shortname = "nt";

The two PHP variables hold the name of your theme (Nettuts in our case), and a shortname which you’ve defined (nt in our case). The shortname is used to prefix all our theme options names, and is usually unique to a particular theme. Moving on, we’ll write some code to automatically generate a list of WordPress categories, rather than having users type in ID numbers. Enter the code below under the already typed code:

$categories = get_categories('hide_empty=0&orderby=name');
$wp_cats = array();
foreach ($categories as $category_list ) {
       $wp_cats[$category_list->cat_ID] = $category_list->cat_name;
}
array_unshift($wp_cats, "Choose a category");

This snippet uses WordPress’ built-in get_categories function to fetch all categories, and then uses a foreach loop to store them in the variable $wp_cats. The options “Choose a category” is then added to the top of the array

Step 4

Now we start entering a list of options for the theme. See below, and paste it into your functions.php file:


$options = array (

array( "name" => $themename." Options",
	"type" => "title"),

array( "name" => "General",
	"type" => "section"),
array( "type" => "open"),

array( "name" => "Colour Scheme",
	"desc" => "Select the colour scheme for the theme",
	"id" => $shortname."_color_scheme",
	"type" => "select",
	"options" => array("blue", "red", "green"),
	"std" => "blue"),

array( "name" => "Logo URL",
	"desc" => "Enter the link to your logo image",
	"id" => $shortname."_logo",
	"type" => "text",
	"std" => ""),

array( "name" => "Custom CSS",
	"desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}",
	"id" => $shortname."_custom_css",
	"type" => "textarea",
	"std" => ""),		

array( "type" => "close"),
array( "name" => "Homepage",
	"type" => "section"),
array( "type" => "open"),

array( "name" => "Homepage header image",
	"desc" => "Enter the link to an image used for the homepage header.",
	"id" => $shortname."_header_img",
	"type" => "text",
	"std" => ""),

array( "name" => "Homepage featured category",
	"desc" => "Choose a category from which featured posts are drawn",
	"id" => $shortname."_feat_cat",
	"type" => "select",
	"options" => $wp_cats,
	"std" => "Choose a category"),

array( "type" => "close"),
array( "name" => "Footer",
	"type" => "section"),
array( "type" => "open"),

array( "name" => "Footer copyright text",
	"desc" => "Enter text used in the right side of the footer. It can be HTML",
	"id" => $shortname."_footer_text",
	"type" => "text",
	"std" => ""),

array( "name" => "Google Analytics Code",
	"desc" => "You can paste your Google Analytics or other tracking code in this box. This will be automatically added to the footer.",
	"id" => $shortname."_ga_code",
	"type" => "textarea",
	"std" => ""),	

array( "name" => "Custom Favicon",
	"desc" => "A favicon is a 16x16 pixel icon that represents your site; paste the URL to a .ico image that you want to use as the image",
	"id" => $shortname."_favicon",
	"type" => "text",
	"std" => get_bloginfo('url') ."http://net.tutsplus.cdn.plus.org/favicon.ico"),	

array( "name" => "Feedburner URL",
	"desc" => "Feedburner is a Google service that takes care of your RSS feed. Paste your Feedburner URL here to let readers see it in your website",
	"id" => $shortname."_feedburner",
	"type" => "text",
	"std" => get_bloginfo('rss2_url')),

array( "type" => "close")

);

That was a large chunk of code, which surely warrants some explanation. So here we go:

  • The PHP variable $options stores the entire list of options for the theme.
  • It is composed of a number of arrays, each with a “type” key to signify how it will be displayed, and what it does.
  • We start with a “type” => “title” array – this will be used to show the themename and a title at the top of the page
  • Each section (General, Homepage and Footer) has a separate list of options.
  • We start a new section by closing any previous sections, declaring a new section using array( "name" => "Footer",
    "type" => "section")
    and opening a new section.
  • Each option can have the options specified below:
    name: The name of the input field.
    desc: A short description explaining what it is to the user.
    id: the id of the field, prefixed by the shortname. It will be used to store as well as access the options.
    type: the input type – select, text or textarea
    options: used to declare an array of options for a select type input.
    std: the default input value, used if no other input is given.

Step 5

Try navigating to WordPress. You will see that there’s no option anywhere to actually view the admin panel page; so how can we view it? Add the following pieces of code to the functions.php file:

function mytheme_add_admin() {

global $themename, $shortname, $options;

if ( $_GET['page'] == basename(__FILE__) ) {

	if ( 'save' == $_REQUEST['action'] ) {

		foreach ($options as $value) {
		update_option( $value['id'], $_REQUEST[ $value['id'] ] ); }

foreach ($options as $value) {
	if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ]  ); } else { delete_option( $value['id'] ); } }

	header("Location: admin.php?page=functions.php&saved=true");
die;

}
else if( 'reset' == $_REQUEST['action'] ) {

	foreach ($options as $value) {
		delete_option( $value['id'] ); }

	header("Location: admin.php?page=functions.php&reset=true");
die;

}
}

add_menu_page($themename, $themename, 'administrator', basename(__FILE__), 'mytheme_admin');
}

function mytheme_add_init() {

}

This function is meant for updating options, as well as adding a menu page. If the options are being saved (indicated by a hidden variable save), then all the options are updated with their new values. If the options are being reset (indicated by another hidden variable with a value reset), then all of the options are deleted. The last line adds a menu page – the parameters are respectively, name and title, the user authorization level required to view the page, the save page and the function used for display/saving (called mytheme_admin in our case). See the mytheme_add_init, a blanbk function? Let that be, we’ll come to it later.

Step 6

Still no theme options page, right? Well, remember the mytheme_admim function we had talked about a few lines ago? We still haven’t written that function. So use the code from steps 6,7 and 8 to write that function. Starting off:

function mytheme_admin() {

global $themename, $shortname, $options;
$i=0;

if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';

?>
<div class="wrap rm_wrap">
<h2><?php echo $themename; ?> Settings</h2>

<div class="rm_opts">
<form method="post">

Pretty simple, right? If the options have been saved, write a message indicating so. Likewise for resets. You’ll notice a class=”updated fade” – WordPress will automatically fade this out in a few sections. Nifty, right? Moving on, we then start the “rm_wrap” div.

Step 7

Carrying on from above, paste in the following code:

<?php foreach ($options as $value) {
switch ( $value['type'] ) {

case "open":
?>

<?php break;

case "close":
?>

</div>
</div>
<br />

<?php break;

case "title":
?>
<p>To easily use the <?php echo $themename;?> theme, you can use the menu below.</p>

<?php break;

case 'text':
?>

<div class="rm_input rm_text">
	<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
 	<input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id'])  ); } else { echo $value['std']; } ?>" />
 <small><?php echo $value['desc']; ?></small><div class="clearfix"></div>

 </div>
<?php
break;

case 'textarea':
?>

<div class="rm_input rm_textarea">
	<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
 	<textarea name="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" cols="" rows=""><?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id']) ); } else { echo $value['std']; } ?></textarea>
 <small><?php echo $value['desc']; ?></small><div class="clearfix"></div>

 </div>

<?php
break;

case 'select':
?>

<div class="rm_input rm_select">
	<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>

<select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
<?php foreach ($value['options'] as $option) { ?>
		<option <?php if (get_settings( $value['id'] ) == $option) { echo 'selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?>
</select>

	<small><?php echo $value['desc']; ?></small><div class="clearfix"></div>
</div>
<?php
break;

case "checkbox":
?>

<div class="rm_input rm_checkbox">
	<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>

<?php if(get_option($value['id'])){ $checked = "checked=\"checked\""; }else{ $checked = "";} ?>
<input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />

	<small><?php echo $value['desc']; ?></small><div class="clearfix"></div>
 </div>
<?php break;

That is one large piece of code! Explanation – using a php foreach loop, each option type is evaluated on a case-by-case basis. We use a switch-case technique for this. The switch variable is the options – the cases are matched and evaluated. Notice the ‘break’ statement after each case? This is to prevent something known as the ‘fall-through’ property. When a case is matched, all successive cases are also executed. This means that if we match case 3, cases 4,5 etc. are also executed. We don’t wan’t that, right? So use a break to stop the switch-case.

If there is an “open” type option – nothing is done. If there is a “close” type options, two divs are closed. The “title” option is only used once – it is an introduction to the theme options. For each of the types “text” (input type=”text”), “select” (dropdowns), “checkbox” and “textarea” (its obvious what those mean), the corresponding input is displayed. Notice the <div class=”clearfix”> – it’s used for clearing floats, which we will do later.

Step 8

We’re coming to the end of that rather massive function. Paste in the code below:


case "section":

$i++;

?>

<div class="rm_section">
<div class="rm_title"><h3><img src="<?php bloginfo('template_directory')?>/functions/images/trans.gif" class="inactive" alt="""><?php echo $value['name']; ?></h3><span class="submit"><input name="save<?php echo $i; ?>" type="submit" value="Save changes" />
</span><div class="clearfix"></div></div>
<div class="rm_options">

<?php break;

}
}
?>

<input type="hidden" name="action" value="save" />
</form>
<form method="post">
<p class="submit">
<input name="reset" type="submit" value="Reset" />
<input type="hidden" name="action" value="reset" />
</p>
</form>
<div style="font-size:9px; margin-bottom:10px;">Icons: <a href="http://www.woothemes.com/2009/09/woofunction/">WooFunction</a></div>
 </div> 

<?php
}

?>

For a “section” type option, I’ve used a counter variable $i. This keeps track of the sections number and conactenates it to the name of the submit button, to have unique submit buttons. There is also a last form at the end for resetting all options. The image used is going to be a transparent image used in our jQuery-fication. Use this very last piece of code to bring our functions into play:

<?php
add_action('admin_init', 'mytheme_add_init');
add_action('admin_menu', 'mytheme_add_admin');
?>

That tells WordPress to add the admin menu.

Step 9

And voila! We have our own awesome admin panel page with a separate menu position for itself. So let’s check it out – click the link. And yuck. That has got to be the most ugly admin panel page ever. So let’s call upon our good friend, CSS! Create a new folder in the nettuts/ directory and name it “functions”. Create a new CSS file there – functions.css. Paste in the following code:

.rm_wrap{
	width:740px;
}
.rm_section{
	border:1px solid #ddd;
	border-bottom:0;
	background:#f9f9f9;
}
.rm_opts label{
	font-size:12px;
	font-weight:700;
	width:200px;
	display:block;
	float:left;
}
.rm_input {
	padding:30px 10px;
	border-bottom:1px solid #ddd;
	border-top:1px solid #fff;
}
.rm_opts small{
	display:block;
	float:right;
	width:200px;
	color:#999;
}
.rm_opts input[type="text"], .rm_opts select{
	width:280px;
	font-size:12px;
	padding:4px;
	color:#333;
	line-height:1em;
	background:#f3f3f3;
}
.rm_input input:focus, .rm_input textarea:focus{
		background:#fff;
}
.rm_input textarea{
	width:280px;
	height:175px;
	font-size:12px;
	padding:4px;
	color:#333;
	line-height:1.5em;
	background:#f3f3f3;
}
.rm_title h3 {
	cursor:pointer;
	font-size:1em;
	text-transform: uppercase;
	margin:0;
	font-weight:bold;
	color:#232323;
	float:left;
	width:80%;
	padding:14px 4px;
}
.rm_title{
	cursor:pointer;
	border-bottom:1px solid #ddd;
	background:#eee;
	padding:0;
}
.rm_title h3 img.inactive{
	margin:-8px 10px 0 2px;
	width:32px;
	height:32px;
	background:url('images/pointer.png') no-repeat 0 0;
	float:left;
	-moz-border-radius:6px;
	border:1px solid #ccc;
}
.rm_title h3 img.active{
	margin:-8px 10px 0 2px;
	width:32px;
	height:32px;
	background:url('images/pointer.png') no-repeat  0 -32px;
	float:left;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border:1px solid #ccc;
}
.rm_title h3:hover img{
	border:1px solid #999;
}
.rm_title span.submit{
	display:block;
	float:right;
	margin:0;
	padding:0;
	width:15%;
	padding:14px 0;
}
.clearfix{
	clear:both;
}
.rm_table th, .rm_table td{
	border:1px solid #bbb;
	padding:10px;
	text-align:center;
}
.rm_table th, .rm_table td.feature{
	border-color:#888;
	}

I won’t explain anything here; it’s pretty clear what each CSS declaration does, and you’re free to customize the layout for your own theme.

Step 10

So now we have a nice CSS file. But how do we add it to the page? After all, we don’t have direct access to the <head> of the document. Remember that blank mytheme_add_init() function we wrote in Step 4? That will come in handy. Change it to this:

function mytheme_add_init() {
$file_dir=get_bloginfo('template_directory');
wp_enqueue_style("functions", $file_dir."/functions/functions.css", false, "1.0", "all");
}

That adds the functions.css file to the head. The location of the file is determined by the template directory.

Step 11

Go look at the page now. Pretty nice looking, isn’t it? But then, you ask, whats the ‘+’ icon for? Well, thats where jQuery comes in!. Create a new file rm_script.js in the nettuts/functions/ folder. Paste in the following code:

jQuery(document).ready(function(){
		jQuery('.rm_options').slideUp();

		jQuery('.rm_section h3').click(function(){
			if(jQuery(this).parent().next('.rm_options').css('display')==='none')
				{	jQuery(this).removeClass('inactive').addClass('active').children('img').removeClass('inactive').addClass('active');

				}
			else
				{	jQuery(this).removeClass('active').addClass('inactive').children('img').removeClass('active').addClass('inactive');
				}

			jQuery(this).parent().next('.rm_options').slideToggle('slow');
		});
});

What this does is – once the DOM loads, all the rm_options slide up. When the ‘+’ icon is clicked, the inactive class is removed from the image and the active class added – making it a ‘-’ icon. The reverse is done when the ‘-’ icon is clicked. The rm_options is then slid up or down(determined by the current CSS state) using the slideToggle function – pretty simple. To add this script, the same mytheme_add_init() function is used. Change it to:

function mytheme_add_init() {
$file_dir=get_bloginfo('template_directory');
wp_enqueue_style("functions", $file_dir."/functions/functions.css", false, "1.0", "all");
wp_enqueue_script("rm_script", $file_dir."/functions/rm_script.js", false, "1.0");
}

The jQuery script will now be active. Gp check it out. Personally, I think its beautiful!

Step 12

Now that we have our theme options page all set up, I’ll just run you through using the options. The code to use the options is as follows:

$var = get_option('nt_colur_scheme');

That will fetch the nt_color_scheme options. See the examples below:

/* To change the CSS stylesheet depending on the chosen color */
<link rel="stylesheet" type="text/css"  href="<?php bloginfo('template_directory'); ?>/<?php echo get_option('nt_color_scheme'); ?>.css" /> 

/*To echo some footer copyright text, with HTML */
<p><?php echo stripslashes(get_option('bl_footer_text')); ?></p>

The variety of uses is limited only by your imagination.

Conclusion

I hope you’ve learned something in this tutorial. This isn’t your standard options panel. This one doesn’t use tables, it’s jQuery enhanced, uses awesome CSS, and is extremely easy to use. The point of this tutorial is to learn – you could always replace collapsible panels with tabs, for example, or even something more advanced. Use your creativity! Feel free to discuss or ask questions in the comments!



Quick Tip: Fully Understanding $.grep()

Quick Tip: Fully Understanding $.grep()

The jQuery method $.grep() is one of those methods that isn’t used as often as it should be. This is mostly because, until you understand exactly what it does, it can be a bit confusing. Hopefully, this video quick tip will explain when and why you would use it.

At its core, $.grep is a simple little method that will filter through an array and sift out any items that don’t pass a particular control. For example, if we have an array of the numbers 1-10, and want to filter out any values that are below 5, we can do:

var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

nums = $.grep(nums, function(num, index) {
  // num = the current value for the item in the array
  // index = the index of the item in the array
  return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

View live demo on JSBin.

Or let’s say that you have an array of numbers and strings, and you want to sift out all of the strings, leaving just an array of numbers. One way that we can accomplish this task is with $.grep.

var arr = '1,2,3,4,five,six,seven,8,9,ten'.split(',');

arr = $.grep(arr, function(item, index) {
  // simply find if the current item, when passed to the isNaN,
  // returns true or false. If false, get rid of it!
  return !isNaN(item);
});

console.log(arr); // 1,2,3,4,8,9

View live demo on JSBin.

For further training, be sure to refer to the jQuery API.



10 Hand-Picked Tutorials for Beginning Web Designers

10 Hand-Picked Tutorials for Beginning Web Designers

So you’re starting to show interest in web design, but are having trouble figuring out where to start? Want to create awesome websites, learn how to code HTML/CSS, and learn about web standards and the user experience? If so, we have a list of hand-picked Envato tutorials that should get you started on your journey!

First Things First

Before you dig into all of these great tutorials written by very talented designers and developers, remember one thing: nothing is impossible and if they can do it…so can you – just like I did few years ago. I began traversing design-related forums (Envato wasn’t present at the time), dug into every web design related post I could find, tried things myself, experienced trial and error until I finally created my first website (which was pretty bad). Don’t be shy to ask for help, we are a great community filled with love to share our knowledge for free! That said, here is a list of, in my opinion, great beginner-level tutorials, which will help you understand the terms “web” and “design”, teach you how HTML and CSS work, and how you can do it all by yourself. Let’s begin.

Please note: some tutorials listed here are part of the Plus Membership program. More info about Plus Tuts could be found here.

Let’s Start with Color Theory…

“The Importance of Color in Web Design”

All too often, I see a great design concept with a poor choice of colors. Part of what makes a great web design “great” is layout, typography and color. When each of these aspects work to compliment each other, great design is born.

Visual Hierarchy in Web Design

On a daily basis I view all sorts of websites and all kinds of designs. One thing in common with successful templates on ThemeForest or with websites around the web is strong visual hierarchy. Often times I see templates that have a great concept going but has poor visual hierarchy. I’ll cover what visual hierarchy is and some great examples in this article.

Common Mistakes in Web Design

Many rejected templates here on Themeforest suffer from the same few common mistakes: typography (font, line-height, letter-spacing, color), alignment (grid), and spacing (padding). In this tutorial, we are going to take a closer look at how to avoid these common errors.

CSS: The Very First Steps

This one is for those who are hoping to take their first steps into web design. This 70 minute Plus video tutorial will assume that you have zero knowledge of CSS. Over the course of the screencast, you’ll learn about the basic syntax, a plethora of different properties, and how to create the beginnings of your very first website.

Design and Code Your First Website in Easy to Understand Steps

In this tutorial, we’re going to design and code our first website in simple, easy steps. This tutorial was written for the beginner with the hope that it will give you the tools to write your own standards-compliant websites! It’s a brand new week; maybe it’s time to learn a new skill!

30 HTML Best Practices for Beginners – Basix

The most difficult aspect of running Nettuts+ is accounting for so many different skill levels. If we post too many advanced tutorials, our beginner audience won’t benefit. The same holds true for the opposite. We do our best, but always feel free to pipe in if you feel you’re being neglected. This site is for you, so speak up! With that said, today’s tutorial is specifically for those who are just diving into web development. If you’ve one year of experience or less, hopefully some of the tips listed here will help you to become better, quicker!

Without further ado, let’s review thirty best practices to observe when creating your markup.

Moving on…

Now that we’ve a basic understanding of theory, and have learned how to design and code a very basic web page, we are ready to move on a bit further. The following articles and tutorials are here to teach you more about the web design process and best coding practices.

Elements of Great Web Design: The Polish

When I put together designs, I usually do so in two phases – Layout and Polish. During the layout phase, I place the main objects on the page usually finishing with something that looks relatively complete. In the second stage – the Polish – I go over the design and adjust colors, type treatments, shadows, layers, and generally clean it all up. In this first of a series of tutorials on web design, we’ll be looking at the Polish.

Designing a Family of Websites

The tutorial I’ve added today is called “How to Design a Family of Website Designs” and is a step-by-step follow-along of a set of WordPress blog designs that I recently did. Because the Photoshop skills involved aren’t that advanced, I’ve spent more time talking about why certain things are done.

From PSD to HTML, Building a Set of Website Designs Step by Step

Today I’m going to take you through my entire process of getting from Photoshop to completed HTML. We’re going to build out a set of 4 PSD mockups of a website that eventually will become a WordPress theme. It’s a massive tutorial, so if you’re going to follow through to the end, make sure you have a few hours to spare!

Last, but Equally Important…

Be Inspired, but Don’t Copy

There’s a thin line between inspiration and copying. We are surrounded with objects and art in our every day life. Finding inspiration for a design is an easy task these days. In this article, I will guide you through the design process of a website I recently finished. I will provide images of websites that inspired me to create a new and unique web layout.

A Freebie to get you Started…

30 Photoshop Web Elements, Backgrounds and Icon Sets (via GraphicRiver)

When you’re designing or building a website, chances are you’re going to need various little elements designed. I personally tend to reuse a lot of the same buttons, menus, icons and so on. Since we launched GraphicRiver earlier this year though we’ve seen a lot of cool little web graphics coming in, in the form of web elements, backgrounds and icons. So I’ve compiled 30 of the best to give you a flavour of what is available over there. Of course don’t forget if you just need a complete PSD design template to build off you can grab those at ThemeForest!

We’re not Done Yet…

Take a few minutes and read these great interviews by some of the leading names in web industry. You’ll be amazed by how much you can learn from these guys!

… and more. Read all of the interviews here.

Final Thoughts…

Every new beginning is tough; the same holds true for web design. I remember myself when I was first learning: hours of HTML/CSS debugging, all while the solution was right there in front of me; but hey, we learn from our mistakes and repetition. I wish I had access to the Tuts+ network when I was first beginning. It could have saved me a lot of time and frustration. Consider this article as the starting point, if you find yourself taking the first steps into this industry. Any questions?

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at [email protected].

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial