Home for Top 10 WordPress Plugins

1. WordPress ‘Branded Admin’ Plugin

Go to download page

If you are a web designer then you must have set up a few WordPress based websites for some of your clients. This plugin enables you to rebrand the /wp-admin pages to follow your own styles. Great if you want to remind your client just who put in all that hard work re-skinning and hacking that theme as they set about trashing your lovely site.

2. ‘Branded Login Screen’ Plugin for WordPress

Go to download page

Completely hides the fact that your site is a WordPress Installation (or at least make it less obvious) with this plugin and the plugin listed previously. Does what it says, allows you to rebrand the login page with your own graphics.

3. GD Star Rating for WordPress

Star rating plugin

Go to download page

Want to put a rating systems on your post content? How about your comments? This nifty plugin allows you to do that and much more. Have statistics generated and displayed in your sidebar by using the GD Star rating widget and have full control over the look and feel of your stars (or whatever graphic you choose!) Looks great too! The author has even put together different star sets for you to upload.

4. Old Post Promoter

Go to download page

Allows you to promote old posts back to the top position on your home page and back into your RSS feed. The Old Post Promoter randomly chooses a post from posts in your blog and updates the timestamp. When the timestamp on the post is updated, the post will appear to be the latest post on your WordPress blog, returning it to the front page of your blog. Ideal if your blog sin’t going to get updated for a while but has planty of content to keep new visitors interested. **IMPORTANT – DO NOT USE IF YOUR PERMALINK STRUCTURE INCLUDES DATESUPDATE YOUR PERMALINK STRUCTURE FIRST!**

5. WordPress Backup

Go to download page

Something we should all do on a regular basis – backup. This handy plugin backs up your upload (images), current theme, and plugin directories. You can specify a regular scheduled backup that can be then sent to an email address of your choice. PLEASE NOTE: You will still need to make sure your database is backed up seperately!

6. Akismet

Bundled with WordPress and for good reason. Without a spam blocker such as this your comment queue would be full of trash in no time at all. Requires a WordPress API key to function. If you haven’t got this plugin activated already, do it now!

7. Google XML Sitemaps

Go to download page

Once set up this plugin will inform Google of any changes or additions made to your site automatically. Generates Sitemap favourable for Google indexing.

8. My Adsense

Go to download page

Manage Google Adsense ads that you wish to display on your wordpress blog posts or sidebars. Easy to use and fully featured.

9. In the Loop

Go to download page

Ever needed to add things to the end of every post or page but had to hack the theme to do it? Well if you don’t want the bother or don’t know how then this plugin may be for you. With this plugin you can add any code you like to your posts and pages without ever having to mess with templates or theme files. The plugin provides an options panel with two input boxes. One is for content you want to appear before your post, the other for after it. Each box comes with a set of options to control whether to show it on Teasers, Single Posts, Pages, The Feed and whether or not to execute PHP. Genius.

10. RSS Includes Pages

Go to download page

And this is STILL at number 10 because I just can’t dispense with this simple plugin. If like me you use WordPress as a CMS to build websites as well as blogs you will no doubt have found that Pages are not included in the RSS feed. Well, with this plugin your problems are over. Simply install, activate and voila, your pages will appear within the feed.

Save Time and Money by Systematizing your Photoshop Workflow

Save Time and Money by Systematizing your Photoshop Workflow

Repetitive tasks can quickly become tedious. As a designer, you probably often find yourself designing the same elements over and over from scratch. STOP!

Wasting time is so old-fashioned. It also means you’re wasting money! So, let’s review some ways that you can automate and systematize your Photoshop workflow. And be sure to download the project base for all of your new designs!

File Tree & Re-usable Project Base

The first step in systematizing your workflow is to organize your files. Identify all common elements you use within your designs.

You may come to a list such as the following:

  • Home Page template
  • About Page
  • Contact Page
  • Services Page
  • Fonts
  • Assets

The Project Base

Consider how your final deliverables are used. If they are shipped to a coding business, be as organized and thorough as possible, including notes and fonts where applicable.

You can ensure that you have perfectly organized themes by creating a package that allows you to “fill in the blanks”, so to speak. Simply copy this folder, assign it to the project by renaming it to the project and get working. This is a very simple and efficient way to work, and means that websites you built four years ago can easily be edited, because everything is packed into its very own place.

Download the Project Base

In the zip file, you’ll find a simple re-useable template starting point. This file contains elements such as dividers, buttons and a pre-gridded template to speed up your design workflow.

See how simple starting a new project is now? It may take a couple of minutes to set-up, but the time saved later is more time for you to be doing what you love best – designing!

Now that we have a solid base to build upon, we can starting filling out our ‘boiler-plater’ with specific files and concepts.

Web Template

The sample template will allow you to create a page of your most used elements, ready for quick inclusion in your latest project.

If you’re a web designer in particular, you’ll find that a lot of your projects, even those different in every possible way – use and re-use common elements.

Begin by building a few re-usable templates. Don’t worry about which elements you wish to include just yet, because you can always go back and look at your previous projects and analyze more popular features – then re-create them here.

Personally, I use just one template. I have a home page (this contains elements such as news bulletins, blog post stylings, menus, logos and call to actions). I can modify this template to suit blog pages, buy it now forms and more.

The page also has a 960.gs pre-applied. This has been included for download at the end of the article, in the template boilerplate.

Once you’re set-up with this concept, you can build designs very quickly. However, you should definitely consider developing your own, and tailor it to your clients and team. You could go further by adding icons, search elements and online store related items – anything to suit your client base.

Grouping & Organizing

The above image demonstrates the tangible difference between an organized layer palette, and a messy one!

When you’re in a real creative flow, it can be difficult to stop and start naming and grouping layers. Photoshop doesn’t really help in this area by default either!

So, take the time as you go to name and group layers. This will help you later when coding the design, or if you ship if off for coding elsewhere.

Name each layer, and try to use a descriptive and short word – such as ‘menu’ for the navigation. Group specific areas, such as the header or a contact form.

This has a two-fold benefit.

  1. You can toggle whole areas (or the whole design) on or off in order to work on the background or other elements.
  2. You can move sections of a design without the need for moving each element. This can save hours per project!

So, take the time to stop every five minutes or so, and name and group each element. You’ll be glad you did!

Make good use of the select tool! You can toggle the select mode between layers and groups. This facilitates mass updating and re-aligning designs, so don’t forget it!

Actions

If you don’t use actions in your work-flow, then you should begin using them immediately.

Photoshop actions are entirely configurable lists of actions Photoshop should carry out automatically. You can create your own, or choose from the bounty available online. If you work on Photographs for example, and have 400 pictures to edit and resize, this would take a long time. Instead, you can create an action that adjusts the contrast, alters the size and then saves the file in .jpg format, blasting through 400 files in seconds! You must use actions!

If you do not have the knowledge, or experience to create your own actions, GraphicRiver has a large selection of actions available for purchase from $1!

The actions on sale range from simple photo effects to this action which can add various pre-formatted text sections such as contact details or blog posts in seconds.

Start using Actions and you will notice a significant increase in your productivity and reduce the amount of times you need to repeat monotonous tasks over and over.

Creating and Using an Action

Making your own action is easy. As an example, we’ll create a simple action to re-size several images at once, then save them.

First off, you need to hit the new action button, on the actions palette.

You shouldn’t need to change any settings as standard, bar changing the name for better organization. Photoshop is now recording your actions. So, all you need to do is re-size the image. Go to image size, and alter the dimensions. The action will change any image to these dimensions. Then hit save.

Finally, press stop on the action palette.

Now, when you press play on the action you’ve created, Photoshop will follow the list of defined actions on your image. Although very simple, an action such as this one could save you hours of monotonous resizing photos and images. This is only a very simple look at actions. They can do so much more, so take your time to get to know them and really use them. The beauty of them is in how you can record basically any action in Photoshop – selecting, changing styles, transforming, re-sizing and saving.

iPhone & UI Design

Do you work with user interfaces? If so, you really need to download a GUI element pack for Photoshop.

There are many available for most popular operating systems and mobile platforms.

For example, if you work with the iPhone, you can download the iPhone GUI pack that contains all elements available in the iPhone interface library, and then simply start designing your app. Simple, quick and much easier than attempting to create these from scratch.

Android GUI Kit

http://www.smashingmagazine.com/2009/08/18/android-gui-psd-vector-kit/

Teehan Lax Kits

The agency, Teehan Lax have several high quality, life-like UI kits. These are great for building an iphone app sales site, or designing the actual UI of an app. Kits are available for the iPhone, Palm Pre and Browsers.

Palm Pre

http://www.teehanlax.com/blog/2009/07/08/palm-pre-gui-psd/

iPhone

http://www.teehanlax.com/blog/2008/11/06/iphone-gui-psd-update-13/

Browser Elements

http://www.teehanlax.com/blog/2008/12/16/browser-form-elements-psd/

Conclusion

I hope we’ve given you some tips that you can use to improve your productivity and efficiency. Photoshop is a wonderful tool, but, if we’re not careful, we can find ourselves repeating the sames tasks over and over. So be sure to implement the above tips and start saving time, money and your sanity!

Download the Project Base

Do you have any Photoshop time-saving tips? Have any ideas on other tasks that could be automated to save time and repetition? Feel free to share them with the community via the comments.



Uncovering jQuery’s Hidden Features

Uncovering jQuery’s Hidden Features :Learn Jquery

jQuery is not always as it appears. There’s a lot of cool stuff going on under the surface, and there are many methods just waiting to be discovered, and many potential usages of jQuery’s API that you may not have considered before. In this article I’ll be taking you through a few of the not-so-obvious things I’ve discovered about jQuery.

1. Understanding jQuery!

When you call ‘jQuery’ what happens?

The jQuery function itself is very simple:

jQuery = function (selector, context) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init(selector, context);
};

Under its skin, the jQuery function (commonly referred to as the “wrapper” function) simply returns an instantiated jQuery object — i.e. an instance of the ‘jQuery.fn.init’ constructor.

This is useful to know; with this information we know that each time we call ‘jQuery’ we’re actually creating a totally unique object with a set of properties. jQuery is clever in that it gives you an object that can be treated as an array. Each of your elements (all together, commonly known as the “collection”) is referenced within the object under a numerical index, just like within an array. And jQuery also gives this object a ‘length’ property, just as you would expect from an array. This opens up a world of possibilities. For one, it means that we can borrow some functionality from ‘Array.prototype’. jQuery’s ‘slice’ method is a good example of this — modified from the source:

/* ... jQuery.fn.extend({ ... */
slice: function() {
    return this.pushStack(
        Array.prototype.slice.apply( this, arguments ),
        "slice",
        Array.prototype.slice.call(arguments).join(",")
    );
},
/* ... */

The native ‘slice’ method doesn’t care that ‘this’ is not a real array– it’ll be fine with anything that’s got a ‘length’ property and [0], [1], [2] etc.

There are some other interesting properties within this jQuery object — ‘.selector’ and ‘.context’ will, most of the time, reflect the arguments that you pass into ‘jQuery(…)’.

var jqObject = jQuery('a');
jqObject.selector; // => "a"

One thing that’s important to note is that jQuery will sometimes give you new jQuery objects to work with. If you run a method that changes the collection in some way, such as ‘.parents()’, then jQuery won’t modify the current object; it’ll simply pass you a brand new one:

var originalObject = jQuery('a');
var anotherObject = originalObject.parents();

originalObject === anotherObject; // => false

All methods that appear to mutate the collection in some way return a brand new jQuery object — you can still access the old object though, via ‘.end()’, or more verbosely, via ‘.prevObject’.

2. Bread-and-butter Element Creation

Central to jQuery’s DOM capabilities, is its element creation syntax. 1.4 brought with it an entirely new way to create your elements quickly and succinctly. E.g.

var myDiv = jQuery('<div/>', {
    id: 'my-new-element',
    class: 'foo',
    css: {
        color: 'red',
        backgrondColor: '#FFF',
        border: '1px solid #CCC'
    },
    click: function() {
        alert('Clicked!');
    },
    html: jQuery('<a/>', {
        href: '#',
        click: function() {
            // do something
            return false;
        }
    })
});

As of 1.4 you can pass a second argument to the jQuery function when you’re creating an element — the object you pass will, for the most part, act as if you were passing it to ‘.attr(…)’. However, jQuery will map some of the properties to its own methods, for example, the ‘click’ property maps to jQuery’s ‘click’ method (which binds an event handler for the ‘click’ event) and ‘css’ maps to jQuery’s ‘css’ method etc.

To check out what properties map to jQuery’s methods, open your console and type ‘jQuery.attrFn’.

3. Serializing your Inputs

jQuery provides a method that you can use to serialize all of the inputs within one or more forms. This is useful when submitting data via XHR (“Ajax”). It’s been in jQuery for a long time but it’s not often talked about and so many developers don’t realise it’s there. Submitting an entire form via Ajax, using jQuery, couldn’t be simpler:

var myForm = $('#my-form');
jQuery.post('submit.php', myForm.serialize(), function(){
    alert('Data has been sent!');
});

jQuery also provides the ‘serializeArray’ method, which is designed to be used with multiple forms, and the ‘param’ helper function (under the jQuery namespace) which takes a regular object and returns a query string, e.g.

var data = {
    name: 'Joe',
    age: 44,
    profession: 'Web Developer'
};

jQuery.param(data); // => "name=Joe&age=44&profession=Web+Developer"

4. Animating Anything

jQuery’s ‘animate’ method is probably the most flexible of jQuery’s methods. It can be used to animate pretty much anything, not just CSS properties, and not just DOM elements. This is how you would normally use ‘animate’:

jQuery('#box').animate({
    left: 300,
    top: 300
});

When you specify a property to animate (e.g. ‘top’) jQuery checks to see if you’re animating something with a style property (‘element.style’), and it checks if the specified property (‘top’) is defined under ‘style’ — if it’s not then jQuery simply updates ‘top’ on the element itself. Here’s an example:

jQuery('#box').animate({
    top: 123,
    foo: 456
});

‘top’ is a valid CSS property, so jQuery will update ‘element.style.top’, but ‘foo’ is not a valid CSS property, so jQuery will simply update ‘element.foo’.

We can use this to our advantage. Let’s say, for example, that you want to animate a square on a canvas. First let’s define a simple constructor and a ‘draw’ method that’ll be called on every step of the animation:

function Square(cnvs, width, height, color) {

    this.x = 0;
    this.y = 0;
    this.width = width;
    this.height = height;
    this.color = color;

    this.cHeight = cnvs.height;
    this.cWidth = cnvs.width;
    this.cntxt = cnvs.getContext('2d');

}

Square.prototype.draw = function() {

    this.cntxt.clearRect(0, 0, this.cWidth, this.cHeight);
    this.cntxt.fillStyle = this.color;
    this.cntxt.fillRect(this.x, this.y, this.width, this.height);

};

We’ve created our ‘Square’ constructor, and one of its methods. Creating a canvas and then animating it couldn’t be simpler:

// Create a <canvas/> element
var canvas = $('<canvas/>').appendTo('body')[0];
canvas.height = 400;
canvas.width = 600;

// Instantiate Square
var square = new Square(canvas, 70, 70, 'rgb(255,0,0)');

jQuery(square).animate({
    x: 300,
    y: 200
}, {
    // 'draw' should be called on every step
    // of the animation:
    step: jQuery.proxy(square, 'draw'),
    duration: 1000
});

This is a very simple effect, but it does clearly demonstrate the possibilities. You can see it in action here: http://jsbin.com/ocida (this will only work in browsers that support the HTML5 canvas)

5. jQuery.ajax Returns the XHR Object

jQuery’s Ajax utility functions (‘jQuery.ajax’, ‘jQuery.get’, ‘jQuery.post’) all return an ‘XMLHttpRequest’ object which you can use to perform subsequent operations on any request. For example:

var curRequest;

jQuery('button.makeRequest').click(function(){
    curRequest = jQuery.get('foo.php', function(response){
        alert('Data: ' + response.responseText);
    });
});

jQuery('button.cancelRequest').click(function(){
    if (curRequest) {
        curRequest.abort(); // abort() is a method of XMLHttpRequest
    }
});

Here we’re making a request whenever the ‘makeRequest’ button is clicked — and we’re cancelling the active request if the user clicks the ‘cancelRequest’ button.

Another potential usage is for synchronous requests:

var myRequest = jQuery.ajax({
    url: 'foo.txt',
    async: false
});

console.log(myRequest.responseText);

Read more about the ‘XMLHttpRequest’ object and also be sure to check out jQuery’s Ajax utilities.

6. Custom Queues

jQuery has a built-in queuing mechanism that’s used by all of its animation methods (all of which use ‘animate()’ really). This queuing can be illustrated easily with a simple animation:

jQuery('a').hover(function(){
    jQuery(this).animate({paddingLeft:'+=15px'});
}, function(){
    jQuery(this).animate({paddingLeft:'-=15px'});
});

Quickly hovering over a bunch of anchors and then hovering over them again will cause the animations to queue up and occur one at a time — I’m sure many of you have witnessed this queuing effect before. If not, check it out here: http://jsbin.com/aqaku

The ‘queue’ method is similar to the well-known ‘each’ method in how it’s called. You pass a function, which will eventually be called for each of the elements in the collection:

jQuery('a').queue(function(){
    jQuery(this).addClass('all-done').dequeue();
});

Passing just a function to ‘queue’ will cause that function to be added to the default ‘fx’ queue, i.e. the queue used by all animations done by jQuery. Therefore, this function will not be called until all current animations occurring on each element in the collection (in this case, all anchors) have completed.

Notice that we’re adding a class of ‘all-done’ in the function above. As outlined, this class will only be added when all current animations are complete. We’re also calling the ‘dequeue’ method. This is very important, as it will allow jQuery to continue with the queue (i.e. it lets jQuery know that you’re finished with whatever you’re doing). jQuery 1.4 provides another way of continuing the queue; instead of calling ‘dequeue’, simply call the first argument passed to your function:

jQuery('a').queue(function(nextItemInQueue){
    // Continue queue:
    nextItemInQueue();
});

This does exactly the same, although it’s slightly more useful in that it can be called anywhere within your function, even within a mess of closures (that typically destroy the ‘this’ keyword). Of course, pre-jQuery-1.4 you could just save a reference to ‘this’, but that would get a bit tiresome.

To add a function to a custom queue, simply pass your custom queue’s name as the first argument and the function as the second:

jQuery('a').queue('customQueueName', function(){
    // Do stuff
    jQuery(this).dequeue('customQueueName');
});

Notice that, since we’re not using the default ‘fx’ queue, we also have to pass our queue’s name to the ‘dequeue’ method, in order to allow jQuery to continue with our custom queue.

Read more about ‘queue’, ‘dequeue’ and ‘jQuery.queue’.

7. Event Name-spacing

jQuery provides a way for you to namespace events, which can be very useful when authoring plugins and third-party components. If needed, the user of your plugin can effectively disable your plugin by unbinding all event handlers that it’s registered.

To add a namespace when registering an event handler, simply suffix the event name with a period and then your unique namespace (e.g. .fooPlugin):

jQuery.fn.foo = function() {

    this.bind('click.fooPlugin', function() {
        // do stuff
    });

    this.bind('mouseover.fooPlugin', function() {
        // do stuff
    });

    return this;
};

// Use the plugin:
jQuery('a').foo();

// Destroy its event handlers:
jQuery('a').unbind('.fooPlugin');

Passing just the namespace to ‘unbind’ will unbind all event handlers with that namespace.

Final Conclusion

So which ones did I miss? Any helpful features that you feel jQuery doesn’t document well enough?

Quick Tip: My Favorite New IDE: WebStorm

Quick Tip: My Favorite New IDE: WebStorm

Over the weekend, Elijah Manor tweeted about a new IDE, called WebStorm, that is currently being offered as a public preview, from JetBrains. After spending a few hours with it, I’m extremely impressed! In this video quick tip, I thought I’d show you some of my favorite features that you, frankly, just don’t see much in other code editors.

Notable Features

  • Not as bloated as other IDEs, like Aptana
  • Git integration
  • Fast intellisense
  • Vertical Selecting (Option + select)
  • CSS lookup on markup (Shift + Command + I)
  • Definition lookup (Control J)
  • Immediately finds formatting errors in your code
  • Advanced debugging
  • Plenty of skins
  • Zen coding implementation! (Such as, ul#nav>li*4>a)
  • Quickly and easily export inline CSS and JS to external files.

What Do You Think?

So, if you’re curious, take some time to look over WebStorm and let me know what you think! I’m still learning it too, so let me know if you found any cool features that I didn’t mention.



How to Create a Simple iTunes-like Slider

How to Create a Simple iTunes-like Slider

When space is at a premium, making use of sliders is the optimal way to present information. Today, we’ll take a look at how to create a slider similar to the one used in the iTunes store.

iTunes Version

Developers often seek the functionality provided by sliders in order to fit lots of information in the space provided. But creating such a slider is not as difficult as you might think. With a little planning and some experimenting, you can create one rather quickly.

I believe a demo is worth a thousand words. Hit the demo and try it out yourselves.

Interested? Let’s get started right away!

Design Goals

Before we start coding, here are a few goals for this widget.

  • Minimize the space taken up by images by making the slideshow’s dimensions the same size of a single image and then fading between them.
  • Provide a vertical carousel of images on the side showing upcoming images.
  • Provide a method to manually move the carousel and the slideshow forward. In this instance, we make use of a simple anchor element.
  • On the carousel, the top most image is the next in line and will be displayed when the next button is clicked.
  • Minimize DOM manipulation as much as possible. That’s not to say we aren’t going to touch the DOM, it’s just that we aren’t going to meddle with the DOM too much.

Plan of Action

There are actually a handful of techniques to make a widget like this. For our purposes today, I’m going to stick with a technique which adheres to a saying:

When in doubt, use brute force.

Step 1: Setup the CSS for the gallery container so that all the main images collapse into taking the space of a single image. I’ll explain this point later below.

Step 2: Setup the CSS for the thumbnail container so that only three images are visible at once.

Step 3: Cycle through the images and assign a class to each thumbnail and image with a numeric index to identify each independently. For example, each image gets a class of thumb-xx where xx is a number.

Step 4: When the next button is clicked, move the carousel one thumbnail up and then display the thumbnail’s corresponding image.

These are the basic steps involved in creating such an effect. I’ll explain each step in detail as we go along.

Step 1: Core Markup

The HTML markup for the demo page looks like so:

<!DOCTYPE html>
<html lang="en-GB">
	<head>
		<title>iTunes slider</title>
		<link rel="stylesheet" href="style.css" type="text/css" />
	</head>

	<body>
    	<div id="container">
        	<h1>Create a simple iTunes-esque slider with jQuery</h1>
		<div>by Siddharth for the lovely folks at Net Tuts</div>
		<p>A simple slider/slideshow which mostly emulates the one on iTunes barring a few changes. Click the down button to cycle the images.</p> 

		<div id="gallery">
    		   <img src="img/1.jpg" />
    		   <img src="img/2.jpg" />
    		   <img src="img/3.jpg" />
    		   <img src="img/4.jpg" />
            	   <img src="img/5.jpg" />
            	   <img src="img/6.jpg" />
	        </div>

                <div id="thumbs">
    	   	   <img src="img/11.jpg" />
    		   <img src="img/22.jpg" />
    		   <img src="img/33.jpg" />
    		   <img src="img/44.jpg" />
            	   <img src="img/55.jpg" />
            	   <img src="img/66.jpg" />
	        </div>

        	<a href="#" id="next"></a>
        </div>

	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript" src="js/mocha.js"></script>

	</body>
</html>

Disregarding the boiler plate code, we have two container elements full of images: one for the main gallery images and one for the thumbnails. I’ve given an ID to both of them so they can be easily accessed from the JavaScript. We also include an anchor element which acts as the next button.

We include the jQuery library and our own script file at the end.

At the end of this stage, our demo page looks like just a list of images.

Tutorial Image

Step 2: CSS Styling

*{
	margin: 0;
	padding: 0;
	border: 0 none;
	outline: 0;
}

body{
	font-family: "Lucida Grande", "Verdana", sans-serif;
	font-size: 12px;
}

p{
	margin: 20px 0 40px 0;
}

h1{
	font-size: 30px;
	font-family: "Myriad Pro", "Lucida Grande", "Verdana", sans-serif;
	padding: 0;
	margin: 0;
}

h2{
	font-size: 20px;
}

#container{
	width: 900px;
	margin-left: auto;
	margin-right: auto;
	padding: 50px 0 0 0;
	position: relative;
}

img{
	display: block;
}

#gallery, #thumbs{
	float: left;
}

#gallery{
	width: 800px;
	height: 300px;
	overflow: hidden;
}

#gallery img{
	position: absolute;
}

#thumbs{
	width: 100px;
	height: 300px;
	overflow: hidden;
}

#next{
	display: block;
	width: 47px;
	height: 43px;
	background: url(img/arrow.png);
	position: relative;
	top: 257px;
	left: 855px;
}

#next:hover{
	background: url(img/arrowmo.png);
}

.clear{
	clear: both;
}

The CSS is pretty self explanatory but there are a couple of points I want you to take note of:

First up, notice that I’ve applied position: absolute to #gallery img. This makes sure that the images are stacked on top of each other instead of one below the other. This way we can later manipulate their opacity to decide which image to show.

Secondly, notice that the thumbs element has its height set to 300px. This is because the thumbnails in the demo are 100px tall each and I want the carousel to show 3 images at once. Essentially, for your own implementation, multiply the height of a thumbnail by the number of thumbnails you want to show at once to find the required height of the element.

Also, take note of the fact that we’ve set its overflow property to hidden to make sure no more than 3 thumbnails are shown at once.

After we’ve styled our slider, it looks like the image below. Notice that almost everything is in place. The last image is stacked at the top and is thus visible.

Tutorial Image

Step 3: JavaScript Implementation

Now that we have a solid framework and some basic styling in place, we can begin coding the required functionality. Note that we make extensive use of jQuery. Feel free to link to Google’s CDN if necessary.

Procuring the Elements and Prepping them

We first need to acquire the images and their corresponding thumbnails so that we can process them.

	var images = $("#gallery img");
	var thumbs = $("#thumbs img");
        var index = 0;

The above snippet will take care of obtaining the list of images and thumbnails, and storing them for later use. We also create a variable called index to denote which element to start from. For now, I’m setting it to start from the first element. Note that index is zero based.

	for (i=0; i<thumbs.length; i++)
	{
		$(thumbs[i]).addClass("thumb-"+i);
		$(images[i]).addClass("image-"+i);
	}

Next, we just iterate through both the lists and and add a class of thumb-xx or image-xx to each element where xx is a number. This lets us look for each individual thumbnail or image independently.

Hooking up the Handler

We now need to create an event handler and attach it to the next button so that we can do something when the button is clicked.

$("#next").click(sift);

The one liner above will take care of that. Essentially, we ask it to call the sift function everytime next is clicked.

function sift()
	{
		if (index<(thumbs.length-1)) {index+=1 ; }
		else {index=0}
		show (index);
	}

This is a very simple event handler actually. We just check to see what element is currently selected. If it is the last, we reset the index so the carousel goes back to the first element, thus creating a pseudo infinite carousel. Otherwise, we increment index by 1.

Next, we call the function show, passing in the index variable as a parameter. We’ll create the function in a bit.

Step 4: Implementing the Core Logic

function show(num)
	{
		images.fadeOut(400);
		$(".image-"+num).stop().fadeIn(400);
		var scrollPos = (num+1)*imgHeight;
		$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);
	}

The show function implements the core functionality of this widget. Let me explain each part.

First, we fade out every image the gallery element contains. Next, we fade in just the required image making use of its class. Since each image can be accessed through its class and we have access to the positional index of the image, we just use the following selector: “.image-”+num

Next, we need to scroll the thumbnail element so that the required image is at the top of the carousel. There are two ways to go on about doing this.

The first method makes use of jQuery’s position property. This lets us find the element’s position relative to its parent element. Unfortunately, I’ve been running into quite a few problems with it and Chrome which means we’ll have to use our second method.

The next method is actually just as simple. Since we can easily obtain the height of a thumbnail and since each thumbnail is required to be of the same height, we can easily just find the product of the nth element’s position in the list and the height of a thumbnail to obtain its offset from the top.

var imgHeight = thumbs.attr("height");

The above line lets us obtain a thumbnail’s height. Remember that a collection of elements can be queried just like a normal element.

var scrollPos = (num+1)*imgHeight;

We now calculate the offset of the thumbnail we need. Since we need the thumbnail of the next element in the list and not of that image itself, we increment it by 1 before multiplying it by the height.

With all this info, we can now scroll the element to the height we need.

$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);

We use jQuery’s animate property to alter the scrollTop property to the value we calculated above. If you are new to jQuery’s animation functions, refer to my earlier article. Essentially, we scroll the element x pixels from the top to create a carousel effect.

Step 5: A Few Tweaks

Polishing the Pseudo Infinite Effect

We are essentially done but a few quick bits of code will make it a little bit more polished.

thumbs.slice(0,3).clone().appendTo("#thumbs");

This line essentially takes the first three thumbnails, copies them over to the end of the list. The slice method selects the first three elements, the clone methods clones these DOM elements and finally the appendTo methods adds them to the passed element.

We can’t just use the appendTo method since it plucks the selected elements from their current position before placing it as required. We need the clone method to copy them first.

We do this to make sure when we approach the final few thumbnails, the illusion of an infinite carousel remains. Else, the user just sees empty blocks which isn’t really what we need.

Making it Auto Rotate

Making the widget auto rotate is actually very simple. Since we have a proper event handler in place, we just have to call the handler every n microseconds. The following line will take care of that:

setInterval(sift, 8000);

In the above code, I’ve asked to call the sift function every eight seconds. Remember, the duration is passed in as microseconds so n thousand equals n seconds.

Initializing the Widget

Currently, the page loads with the widget uninitialized. We’ll need to rectify this. All we need to do is to call the show function passing in the starting position as a parameter.

After you’ve attached the event handler, add this:

show(index);

The Final Code

And we are done! The final code looks like so:

$(document).ready(function()
{
	var index = 0;
	var images = $("#gallery img");
	var thumbs = $("#thumbs img");
	var imgHeight = thumbs.attr("height");
	thumbs.slice(0,3).clone().appendTo("#thumbs");
	for (i=0; i<thumbs.length; i++)
	{
		$(thumbs[i]).addClass("thumb-"+i);
		$(images[i]).addClass("image-"+i);
	}

	$("#next").click(sift);
	show(index);
	setInterval(sift, 8000);

	function sift()
	{
		if (index<(thumbs.length-1)){index+=1 ; }
		else {index=0}
		show (index);
	}

	function show(num)
	{
		images.fadeOut(400);
		$(".image-"+num).stop().fadeIn(400);
		var scrollPos = (num+1)*imgHeight;
		$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);
	}
});

Conclusion

And there you have it: we’ve created a simple but useful slider. Hopefully you’ve found this tutorial interesting and useful. Feel free to reuse this code elsewhere in your projects, and chime in within the comments if you are running into difficulties.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!



Redesign and Other Tuts News

Redesign and Other Tuts News

Over the last three days we’ve been steadily rolling out a new Tuts+ theme across all 8 sites. The new design is a refinement more than a big change, with lots of little improvements in usability and more suited to big screens. Read on to learn more about the redesign and lots of news about Plus!


1 The Plus Project

As you may know we have some pretty big plans for these Tuts+ sites. While today they are humble little tutorial blogs, we’ve thought for some time that it would be cool to build an entire platform for education. We’re going to call that platform Plus. You’ll know Plus content as our premium content, but no longer.
Our premium content is now ‘Premium’ (go figure!) and Plus is the brand for the educational platform we’re building, which, just like Psdtuts+, will be completely free for the most part.

With Tuts+ well established now, we’ve finally begun work on the project! We’ve acquired the domain Plus.org which will be the home of the new platform (yay for our first four letter domain!) We’ve also brought over our resident code genius Ryan Allen (who built our ActiveDen platform all by himself back in 2006) to team up with Tuts+ developer extraordinaire Fred Wu and kick ass front-end guru Derek Herman. And Skellie and I have been busy spec’ing out the plans for the new site, and it’s pretty, damn cool if I do say so myself!

Right now the Tuts+ sites are fairly passive, but we’d like to get the whole community involved in writing, teaching, answering questions and generally learning. The new Plus.org platform promises to incorporate all that plus some nifty ideas we’ve taken from gaming to come together into a social education platform.

It’s going to take a long time and we’re going to roll it all out in pieces over the next 2 years. We’re super excited about it all, and I hope I’ll have more updates in the coming months!


2 Creative Sessions and Mobiletuts+

While Plus.org will take a long time, we do have some new goodies coming much sooner including Creative Sessions which is being built now, and also Mobiletuts+ which will be all about mobile development!


3 Server Update

About a week and a half ago we had some major problems with our servers. I’m happy to say that we’ve now completely resolved these issues by moving hosts and reengineering our hosting setup completely from scratch. The new setup is much quicker and has a much greater capacity for growth, so fingers crossed, that will be the last server outage for a long time to come!


4 The Redesign

The new theme has a few neat features you may want to check out including:

  • Basix!
    While Tuts+ has always been known for intermediate to advanced level content, we’ve been thinking it’d be good to separate out tutorials and articles better suited to people just getting started. So we’ve created the Basix tag for quick browsing. You’ll find it in the top menu, and expect to see more Basix content soon as we beef up our library of novice-friendly content.
  • Easy access to Videos, Tips and Premium Posts
    We’ve also started tagging videos, tips and Premium membership posts so that along with Basix content you can quickly find what you’re after. We’re generally going to be working to clean up our category/tagging across the network in the coming months to get it more standardized.
  • Tutorial Details on Posts
    We’re also going to start standardizing all tutorials to have a "Tutorial Details" section at the top with difficulty and other pertinent details. Eventually we’ll get all the archives updated … but with over 2000 tutorials, that will take a while!
  • Bigger, more readable content area
    We’ve expanded the site to be optimized for bigger 1280px wide screens, with a bit of JavaScript to resize for smaller resolutions. This has given us the space to clean up the content area to be a bit bigger and more readable generally.
  • Latest Creattica content for inspiration
    We’ve also started porting over the latest Creattica content into our sidebars. There’s actually a redesign of Creattica coming in the next few weeks and we’ll be expanding the gallery to cover even more types of inspiration. The new sidebar widget will give even more exposure to those talented creatives on Creattica!
  • General UI Improvements
    Most of the improvements on the new design are small, subtle improvements such as a reduction in the number of clicks needed to browse categories, a clearer search field, faster loading pages and generally cleaner, more optimized code.

One change that we have also made is to remove the community link feed. Over the years this was a great way to get exposure to community links, but unfortunately was also home to a lot of spam. So with this iteration we’ve left it behind.

Also at the moment sites with Flickr groups don’t have it showing, but don’t worry that’ll be back. There’s just a problem with our Flickr plugin at the moment!!

There are still some more tweaks to do to the new design and a lot of post formatting to do to get our archives matching up with the new theme. But for all intents and purposes the new theme is now alive and well! Enjoy!



Quick Tip: The HTML 5 Audio Element

Quick Tip: The HTML 5 Audio Element

As of Firefox 3.5, Chrome 3, Opera 10.5, and Safari 4, we can take advantage of many of the new HTML 5 features, including native audio support without the need for Flash. As you’ll find, we only to create the new <audio> element, and set a few attributes. In this four minute video quick tip, we’ll review the mark-up, and also a quick way to play audio with jQuery.


The Audio Element

<audio autoplay="autoplay" controls="controls">
	<source src="file.ogg" />
	<source src="file.mp3" />
</audio>

The audio element accepts a handful of attributes, most notably:

  • autoplay : Immediately plays the file when the page loads.
  • controls : Displays the player on the page.
  • preload : Immediately begins buffering the file. (values = none, auto, metadata)
  • src : The path to the file name. It’s a better practice to load the file via the child “source” element instead.

Mozilla and Webkit don’t fully get along just yet, when it comes to the audio format. Firefox will want to see an .ogg file, while Webkit browsers will work just fine with the common .mp3 extension. This means that, at least for now, you should create two versions of the audio. I recommend that you use a quick and simple online tool, called Media.io, to convert your mp3 over to the ogg format.

When Safari loads the page, it won’t recognize that .ogg format, and will skip it and move on to the mp3 version, accordingly. Please note that IE, per usual, doesn’t support this, and Opera 10 and lower can only work with .wav files.


Loading Audio with jQuery

// Slightly modified from video version.
$(document).ready(function() {
    // Create an audio element, and set it to autoplay,
   // and show the player when the page loads.
    var audio = $('', {
      autoPlay : 'autoplay',
      controls : 'controls'
    });

    // Call our addSource function, and pass in the audio element
    // and the path(s) to your audio.
    addSource(audio, 'audioFile.ogg');
    addSource(audio, 'audioFile.mp3');

    // When some event is fired...
    $('a').click(function() {
     // Add the audio + source elements to the page.
      audio.appendTo('body');
      // Fadeout the anchor tag to keep the user from clicking it again.
      $(this).fadeOut('slow');
      return false;
    });

   // Adds a source element, and appends it to the audio element, represented
   // by elem.
    function addSource(elem, path) {
      $('').attr('src', path).appendTo(elem);
    }

});

Please note that we can go much, much further with this, including how to stop the audio, change the volume, etc. This quick three minute tip is just to whet your appetite. If you’d like to delve deeper, let us know and I’ll schedule a full thirty-minute tutorial on the topic!



12 Steps to MooTools Mastery

12 Steps to MooTools Mastery

This tutorial is about understanding and mastering the MooTools library. It does so by offering a high level introduction to the history and foundations of the Core library: where to start, where to explore, what to master, and more.

Tutorial Details

  • Program: MooTools
  • Version: 1.2.*
  • Difficulty: Intermediate
  • Estimated Completion Time: 1 hour

1: Prototypal Inheritance

step 1

The foundation of the MooTools framework is really in the prototypal inheritance model of JavaScript. In classical languages, like C++ or Java, a class represents something like a data type or what Jeff Mott called a “blueprint.” These blueprints are then used in the creation of objects. In fact, in these languages nothing is actually created until the “new” operator explicitly invokes them.

With JavaScript however, everything is created immediately, even before you instantiate the objects with the “new” operator. As a prototypal language, this effectively means no blueprints, no “classes”. Instead, we go about using some objects as fully operational bases for other objects. As Douglas Crawford said, in precisely this way JavaScript becomes “more capable and offers more expressive power.” Let’s take a look:

function Nerd(iq) {
    this.iq = iq;
    this.glasses = true;
    this.pants = 'high';
}

function SuperPowers() {
    this.strongerThanLocomotive = true;
    this.fasterThanBullet = true;
    this.canLeapBuildings = true;
}

Nerd.prototype = new SuperPowers();

Nerd.prototype.willWinGirl = function (hotness) {
    if(this.iq > (hotness * 20) || this.strongerThanLocomotive){
        console.log('maybe');
    }
    else {
        console.log('nope');
    }
}

new Nerd(140).willWinGirl(10); // logs "maybe"

The example above is actually a rather popular means of introducing the concept of prototyping. However, if you’re finding this a little too abstract, perhaps a better way to approach this would be to look at prototyping a native JavaScript constructor like String, Array, etc. For example:

Array.prototype.eachhhh = function (fn) {
    for (var i = 0, l = this.length; i < l; i++) fn(this[i]);
}

[0,1,2,3].eachhhh(function(item){
    console.log(item); // logs: 0,1,2,3
});

Prototyping simple code patterns like the for loop above can save tons of time when working on larger projects. When using the MooTools framework, it’s important to begin thinking of every constructor as being extendable; this is going to save you time down the line and make your code much more flexible. Furthermore, it’s precisely this method of inheritance that is at the core of MooTools, and harnessing this frameworks power means making use of prototyping. Of course, what MooTools does is make this process a whole lot easier for you to access and take advantage of, but we will get into exactly how it does this later on in the article.

2: Object Literal Notation

step 2

Wayyyy back in 2006, Chris Heilman was already getting fanatical about the object literal syntax… talking about sliced bread and other craziness. At any rate, for that very reason I’m not going to dwell on this subject too much, instead I’ll assume that you’ve come across this syntax at some point or atleast can grasp it by the simple example below.

//this is not object literal notation
var variable1 = null;
var variable2 = false;

function1(){
// some code
}

function2(){
// some code
}

// the above becomes object literal notation below... 

var SomeVariableName = {

    variable1: null,
    variable2: false,

    init:function(){
    },

    function1:function(){
    // some code
    },

    function2:function(){
    // some code
    }
}

Like most programming languages, in JavaScript there exist a large number of stylistic preferences and “best practices.” When working with MooTools you’ll find there to be no shortage of these, including: not chaining excessively, capitalizing your class names, comma separating variable declarations, etc…. However, among these, object literal notation is perhaps most fundamental to understanding not only the way in which the MooTools framework itself is structured, but actually how to take advantage of this framework in developing your own code. We’ll develop this idea further throughout the rest of this article and as you’ll see, all the examples from this point forward will be taking advantage of this syntax.

3: The Class Constructor

step 3

If JavaScript doesn’t have “classes,” then why is there all this hype around Motools and classes? In May of last year, Aaron Newton published an excellent comparative piece on jQuery and MooTools. Among other things, he addressed precisely this question of classes in a very succinct way: “Despite its name, the MooTools Class function is not really a class nor does it create them. It has design patterns that might remind you of classes in a more traditional programming language, but really Class is all about objects and prototypal inheritance.”
As Aaron goes on to detail, the MooTools framework is pushing for powerful and ultimately simple ways to organize and structure your code, ways which are elegant but also familiar, and not just semantically, but in their capacity to behave in classical design patterns. In fact, you’ll find utilizing “classes” in your code base opens up your code to many powerful programming patterns: the mediator, the mixin, etc…

A simple MooTools class will look something like this (notice the syntax):

var YourClass = new Class({

    variable1: false,

    initialize: function(){
        this.toggleVariable();
    },

    toggleVariable: function(){
        this.variable1 = !variable1;
    }

});

var yourClassInstance = new YourClass();
yourClassInstance.toggleVariable(); // this.variable1 == false

Not too complicated, right? Once you begin structuring your code in classes like these, you’ll find that your code repository will become not only a lot more organized and manageable, but actually smaller!

4: Class.Mutators

step 4

So how exactly does it become smaller? Returning to JavaScript’s prototypal inheritance model and how it relates to the Class constructor, MooTools provides us with Extends and Implements. As properties, both are fundamental to the production of your MooTools subclasses and make this whole protyping mess a bit more intuitive. At a high level, Extends gives your subclass access to all the methods of it’s base class, where methods and properties of the same name are overwritten (not to worry, they’re still accessible through the parent() method). Similar to Extends, Implements adopts properties from one or more other classes, but without the inheritance model.

Consider briefly Digitarald’s fancy upload plugin for Mootools. In this program Harald defines several classes, one of which is called the ‘File’ class. File houses the core functionality that a file object needs to interface with his uploading program and for this very reason is perfect for being extended; one might create an “Image File” subclass, a “Text File” subclass, etc. By modeling your code in this way, you are able to build your code up, rather than out. Consider the example below for how to use Extends:

var YourSubClass = new Class({

    Extends: YourClass, //here we are extending "YourClass" from our previous example

    variable2: false,

    initialize: function(){
        this.parent(); // this will call the initialize function from the bass Class "YourClass"
    },

    //here we are overwriting the toggle Variable function of "YourClass" with a new function
    toggleVariable: function(){
        this.variable1 = !variable1; // notice variable1 from "YourClass" is still accessible in YourSubClass
        this.variable2 = !this.variable1;
    }
});

5: Custom Events and Options

step 5

The most common usecase I find with Implements is including either the Events constructor or the Options constructor in my classes. As the name suggests, implementing Events allows for both the attachment and firing of custom events on your object, like onComplete, onFailure, onSuccess, onAnything. This level of abstraction becomes particularly useful when you begin sharing your code across several projects, where events behave as mediators between your current project and your plugins. In this way you can finally get away from those nasty one-to-one, bound relationships in your plugins. For example:

var YourSubClass = new Class({

    Implements: Events, //here we tell MooTools to implement Events in our sub class (this wont effect the bass "YourClass")

    Extends: YourClass,

    variable2: false,

    initialize: function(){
        this.parent();
    },

    toggleVariable: function(){
        this.variable1 = !variable1;
        this.variable2 = !this.variable1;
        //afterToggle() -- calling "afterToggle" would have made this function a necessary include of YourSubClass
        this.fireEvent('toggled'); //instead a custom event is fired called "toggled"
    }
});

var yourSubClassInstance = new YourSubClass();

var afterToggle = function(){
    alert('i\'ve just been toggled!');
};

//here we add a listener for the custom event, just like we would any other event
yourSubClassInstance.addEvent('toggled', afterToggle);

Besides Events, often you will want to Implement MooTools’ Options. This utility class allows you to automate the setting of a list of optional properties to be set on an instance of your class. Again, this can be very helpful when writing plugins for various projects, allowing for the circumstantial customization of certain properties of your object. Consider the example below:

var YourSubClass = new Class({

    //One of the many cool things about the implements property is that it excepts an array.
    Implements: [Events,Options], //Here we include Options

    Extends: YourClass,

    //options are set if the invoker does not explicitly specify a value.
    options: {
        variable2: false
    },

    initialize: function(options){
        this.setOptions(options); //sets the options
        this.parent();
    },

    toggleVariable: function(){
        this.variable1 = !variable1;
        this.options.variable2 = !this.variable1;
        this.fireEvent('toggled');
    }
});

// this will start the class with variable2 = true.
var yourSubClassInstance = new YourSubClass({
    variable2: true
});

6: Binding

step 6

As your programs become more complex, a proper understanding of scope becomes invaluable. Scope is the way variables in JavaScript relate to any single point of execution — there are global variables, which are variables that can be referenced from anywhere in the document and occupy the lowest executing level, local variables, which are variables limited to their immediate containing functions or closures, and finally, self references, the “this” keyword, which are JavaScript’s way of referencing the context of the current point of execution.

var global = true; //global variable;

var aFunction = function(){
    var local = true; //local variable
}

$('button').addEvent('click', function(){
    this.addClass('clicked'); // self reference
});

When referencing a variable in your code, JavaScript bubbles from it’s current executing position through all accessible levels of variables until it locates the first and nearest occurrence of a positive match. This behavior is often less than desirable, particularly when dealing with events inside of object literals as they house their own self references. Often developers rely on what are called “lexical closures” to circumvent problems like these, storing the self reference in a variable of a different name. However, MooTools provides an alternative means of achieving this through their bind() method, which is not only cleaner, but a lot more elegant. Consider the example below:

...

    addEvents: function(){
        $('button').addEvent('click', function(){
            //binding substitutes the current self reference for that of the object passed in
            this.toggleVariable();
        }.bind(this)); // here we bind this to the click event handler
    },

    toggleVariable: function(){
        //code
    },

...

7: The Element Constructor

step 7

In the example above we targeted an already existing element in the DOM and added an event listener to it. However, it’s not uncommon today that you will see entire web apps load their content dynamically using JavaScript. With the evolution of JSON, being able to generate markup on the fly has become increasing necessary. Enter the MooTools Element constructor. The novel thing about this constructor is that it maintains it’s readability despite it’s large capacity for optional properties (Again, thanks to the object literal notation!). Element accepts an events object, a styles object, plus any individual properties like class, id, src, href, title, etc. That said, it’s also loaded with a ton of methods, the complete list of which is available from the MooTools docs here. Below is a simple example of how to get started:

var el = new Element('div', {
    id: 'button',
    'html': 'hellloooo',
    styles: {
        display: 'block',
        position: 'relative',
        float: 'left
    },
    events: {
        click: function(){
            //your code
        }
    }
});

8: DOM Manipulation

step 8

Now that you have your dynamic element, wouldn’t it be great to insert it into the DOM? MooTools provides a really handy list of methods for just that, including:

  • inject – places one element relative to the calling element : ‘before’, ‘after’, ‘top’, ‘bottom’
  • grab – like inject but in reverse
  • adopt – works like grab accept it can accept an array of elements and you can’t specify an exact relation
  • wraps – Works like grab, but instead of moving the grabbed element from its place, this method moves this Element around its target

Of these methods, I’ve found adopt’s ability to accept an array of elements absolutely indispensable, especially when structuring larger quantities of dynamic markup. Consider the example below:

var el = new Element('div', {
    id: 'button',
    styles: {
        display: 'block',
        position: 'relative',
        float: 'left
    },
    events: {
        click: function(){
            //your code
        }
    }
}).adopt(

    this.createSpan(), // returns an element which can later be overwritten by a subclass

    new Element('a', {
        href: 'http://somewebsite.com'
    }).adopt(

        new Element('strong', {
            'html': 'world'
        })

    )
).inject($(document.body),'top');

The example above makes for a truly object oriented approach to DOM manipulation. When you become a super MooTools ninja, jedi, junky, nerd, you can use the method above to begin abstracting out functions which return elements or arrays of elements, making it possible for your subclasses to target specific methods in modifying your display. Awesome.

9: Request.JSON & Request.JSONP

step 9

JavaScript Object Notation or JSON is the lightweight data-interchange format that everyone loves (especially after working with XML). The great thing about JSON of course is that it’s structure is recognized natively by JavaScript, and with many large sites opening up their data to the public via APIs, there’s really no reason why you shouldn’t invest the time to get familiar with it. No longer a cross browser nightmare, whether you’re pushing data to a back-end service or requesting another batch of tweets from twitter, the MooTools Request constructor makes JSON and JSONP incredibly simple. It works with several event listeners and recently a timeout, which is completely neccessary once you start getting into JSONP. (Which you should! It’s so fun.) Here’s a simple example:

var JSONRequest = new Request.JSON({
    url: "http://yoursite.com/tellMeSomething.php",
    onFailure: function(){
        alert('oh nooo!');
    },
    onSuccess: function(response){
        alert('hooray!: ' + response.result);
    }
});

10: Fx

step 10

At a high level, the Fx constructor allows you to modify any CSS property of an HTML element, which itself accepts a single element and a series of optional properties (duration, transition type, etc.) to create smooth animation effects of colors, slides, scrolls, etc. What’s more, the Fx constructor is fully compatible with Robert Penner’s Easing equations, which are a great way to add a touch of uniqueness to your transitions like bounce, elastic, sin, etc.

If you’re “hardcore” you can actually achieve all of the animation effects using either Fx.Tween(single css style animation) or Fx.Morph (multiple simultaneous style animations). Of course, beyond these there’s Fx.Slide, Fx.Scroll, Fx.Accordian, etc. Here’s a simple example using Fx.Tween:

var myFx = new Fx.Tween($('button'));
myFx.start('background-color', '#000', '#f00'); //this tweens the background color of the button element.

If you’re dying to get deeper into this topic, check out Consider Open’s fx tutorial for a fairly comprehensive introduction to the constructor.

11: Swiff

step 11

Originally appearing in Digitarald’s fancy upload, the Swiff object allows your page’s JavaScript to communicate with Flash. This makes it substantially easier to interact with Flash’s unique functionality like video, sound, file streaming, and clipboard accessing features. More over, Swiff allows you to pass values and manipulate the Flash movie using conventions you’re familiar with from JavaScript and Mootools. Integrating flash in this way is particularly useful as we begin taking steps towards offering HTML5 as a progressive enhancement, where, barring user’s have the flash plugin, Swiff can be used to control audio or video on older browsers. Meanwhile, check out the simple example below:

var flashObject = new Swiff('sounds.swf', {
    id: 'mySoundManager',
    width: 1,
    height: 1,
    vars: {
        myVariable: true, //pass variables into flash on load
    },
    callBacks: {
        //call custom events from your flash object
        someEvent: function(){
            //code
        }
    }
});

Swiff.remote(flashObject, 'playMySound') //calls the function "playMySound" from within flash

12: Mootools More & Forge

step 12

Now with over fifteen members contributing to the official more plugin repository and over one hundred unofficial plugins already on Forge, it’s no surprise that “Community” is what the MooTools team wanted us as developers to take away from 2009. Indeed people have truly embraced this framework, and now with Forge, we have a great place to meet each other and begin sharing ideas. You’ll find David Walsh, Aaron Newton, 3n, and many others actively contributing amazing code and facilitating an environment capable of both inspiration and utility. In the end, the most helpful way to pick up the MooTools framework is by engaging with the developers around you and ultimately understanding what they are working on and how they’re going about it.

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



Coding a Complex Design into CSS and HTML: New Plus Tutorial

Coding a Complex Design into CSS and HTML: New Plus Tutorial

Today, we’re going to be taking the PSD website design, from Mahmoud’s Psdtuts+ Tutorial ,and coding it into valid, semantic HTML and CSS. Along the way, we’ll go over some essential CSS techniques, such as image replacement, sliding doors, and CSS sprites. This is a monster of a tutorial, as the design is a bit complex. Nevertheless, a relative beginner should be able to follow along, so put on a pot of coffee and let’s get started!

Help give back to Nettuts+ by becoming a Premium Member!

Final Product

Become a Premium Member

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. 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.



How to Add Custom Configuration Settings for an (ASP).NET Application

How to Add Custom Configuration Settings for an (ASP).NET Application

Since its release, ASP.NET applications and components have looked to the web.config file to load any settings they need to function. However, adding custom settings to add flexibility and robustness to an application or component isn’t as straight forward as most would like. This article teaches you how to write the necessary classes to handle XML configuration elements and use the settings they contain within your code.

Tutorial Details

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

The .NET Framework provides a wide variety of settings that can be configured within
web.config to modify the behavior of one or more built-in components within the
application. For some developers, sticking solely with the settings provided by
the .NET Framework is sufficient. But many more developers find they need to control
a broader collection of settings ñ either for components (written by themselves
or a third party), or simply a set of values they find themselves using throughout
their application.

The web.config file does allow you to set custom settings with the <appSettings/>
element, but it doesn’t allow anything other than simple key/value pairs. The following
XML element is an example of a setting contained within <appSettings/>:

<add key="myKey" value="myValue"/>

Key/Value settings certainly can be helpful in many circumstances, but <appSettings/>
settings simply aren’t flexible enough for robust or complex components or settings.

Thankfully, Microsoft enables developers to write classes that add programmatic
access to custom configuration settings contained within web.config.

The Configuration Section

Settings within web.config are categorized into configuration sections. For example,
the settings contained within the <system.web/> section pertains to ASP.NET
settings for your application. You can change the authentication scheme of your
app, as well as add or remove HTTP handlers to perform specific functions for specific
file types. The <system.webServer/> section allows you to control many of
IIS7ís settings without having direct access to IIS7.

A configuration section is required of all settings not contained within the <appSettings/>
element. So itís a good idea to design the XML structure of your configuration settings
before writing any code.

The configuration used as an example in this tutorial is for a component that retrieves
RSS or Atom feeds. It doesn’t do any parsing, as that is beyond the scope of this
tutorial. Instead of hard coding the list of feeds to retrieve, the component looks
to its configuration to contain the names and URLs of the feeds to retrieve. The
component is called FeedRetriever, and the desired XML structure of its configuration
looks like this:

<feedRetriever>
    <feeds>
        <add name="Nettuts+" url="http://feeds.feedburner.com/nettuts" cache="false"/>
        <add name="Jeremy McPeak" url="http://www.wdonline.com/feeds/blog/rss/" />
        <add name="Nicholas C. Zakas" url="http://feeds.nczonline.net/blog/" />
    </feeds>
</feedRetriever>

The <feedRetriever/> element defines by the configuration section. As a general
rule, a configuration section should share the name of the the component it is designed
for. The <feedRetriever/> elements only child is the <feeds/> element.
Think of this element as a collection of feeds because it contains several <add/>
elements (think of the Add() method that most collection objects have). The choice
of using an element named "add" may seem strange at first, but the <add/>
element is used throughout the majority of built-in configuration sections. So using
it here simply follows the design practices put forth by Microsoft.

These <add/> elements use the name, url, and cache attributes to set certain
settings for each feed. Naturally, the name and url attributes are required, but
the cache attribute is not, and should default as true.

The above configuration is simple. The <feedRetriever/> element could be modified
to contain another child, called <globalSettings/>, to contain settings that
would apply to all feeds. The <add/> elements could also use additional attributes,
such as cacheTime and requestFrequency, to control how long a feed is cached and
how often it is requested from the remote host. The only limit to the extensibility
and configurability is your imagination.

Writing the Configuration Handler

After designing the XML structure, the next step is to write a configuration handler
to process the settings defined in the XML. The handler is primarily a class that
inherits from <a title="MSDN Documentation for System.Configuration.ConfigurationSection"
href=”http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx”
target=”_blank”>System.Configuration.ConfigurationSection, but it also incorporates
the use of other classes ñ such as classes that derive from <a title="MSDN Documentation for the System.Configuration.ConfigurationElement class."
href=”http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement.aspx”
target=”_blank”>System.Configuration.ConfigurationElement and <a title="MSDN Documentation for the System.Configuration.ConfigurationElementCollection class."
href=”http://msdn.microsoft.com/en-us/library/system.configuration.configurationelementcollection.aspx”
target=”_blank”>System.Configuration.ConfigurationElementCollection.
Classes based on ConfigurationElement represent individual elements; it is the building
block of a configuration section. Types that derive from ConfigurationElementCollection
simply represent elements that contain more than one type of element. From the configuration
listed above, the <feeds/> element is represented by a class that derives
from ConfigurationElementCollection, and the <add/> elements are represented
by a ConfigurationElement-based class.

Representing the <add/> Element

Youíll start with the <add/> element by representing it with a class called
FeedElement (derived from ConfigurationElement). This class, and future configuration-related
classes, reside in the FeedRetriever.Configuration namespace.

Every ConfigurationElement object functions as an indexer for its internal collection
of property values. It is this internal collection, along with .NET attributes,
that enables you to map the <add/> elementís attributes to the properties
of the FeedElement class.

The following code is the complete code for the FeedElement class:

public class FeedElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get { return (string)this["name"]; }
        set { this["name"] = value; }
    }

    [ConfigurationProperty("url", IsRequired = true, DefaultValue = "http://localhost")]
    [RegexStringValidator(@"https?\://\S+")]
    public string Url
    {
        get { return (string)this["url"]; }
        set { this["url"] = value; }
    }

    [ConfigurationProperty("cache", IsRequired = false, DefaultValue = true)]
    public bool Cache
    {
        get { return (bool)this["cache"]; }
        set { this["cache"] = value; }
    }
}

The ConfigurationElement class serves as an indexer to an underlying collection
of configuration properties (hence the indexer notation of this[keyValue]). By using
the this keyword and accessing the underlying property with a string key, you can
get and set the property’s value without needing a private field to contain that
data. The underlying property collection stores data as type Object; therefore,
you have to cast the value as the appropriate type if you want to do anything with
it.

The properties that represent XML attributes are decorated with <a title="MSDN – Documention for the ConfigrationPropertyAttribute class."
href=”http://msdn.microsoft.com/en-us/library/system.configuration.configurationpropertyattribute.aspx”
target=”_blank”>ConfigurationPropertyAttribute attributes. The first parameter
of of the ConfigurationPropertyAttribute attribute is the name of the XML attribute
found within the <add/> element. Following the first parameter are a set of
any number of named parameters. The following list is a complete list of possible
parameters:

  • DefaultValue ñ Gets or sets the default value for the decorated property. This parameter
    is not required.
  • IsDefaultCollection ñ Gets or a sets a Boolean value indicating whether the property
    is the default property collection for the decorated property. This parameter is
    not required, and the default is false.
  • IsKey – Gets or sets a Boolean value indicating whether this property is a key property
    for the decorated element property. This parameter is not required, and its default
    value is false.
  • IsRequired ñ Gets or sets a Boolean value indicating whether the decorated element
    property is required. This parameter is not required, and its default value is false.

The default value of "http://localhost" for the Url property is not an
error. The .NET Framework also grants you the ability to decorate the properties
with validator attributes ñ such as the <a title="MSDN Documentation for the RegexStringValidatorAttribute class."
href=”http://msdn.microsoft.com/en-us/library/system.configuration.regexstringvalidatorattribute.aspx”
target=”_blank”>RegexStringValidatorAttribute decorating the Url property.
This validator takes the value of the Url property and validates it against the
regular expression provided to the attribute; however, it also validates the Url
property before it contains the data from the XML element. The default value of
the Url property is an empty string when a FeedElement object is first created.
An empty string does not validate against the provided regular expression, so the
validator throws an ArgumentException before any data is loaded from the XML file.

There are two possible workarounds for this problem. The first approach modifies
the regular expression to allow empty strings. The second approach assigns a default
value to the property. It does not matter in this particular case. Even with a default
value, the url attribute is still a required attribute in the <add/> element
– the application throws a ConfigurationErrorsException if an <add/> element
does not have a url attribute.

There are several other validator attributes in the System.Configuration namespace
to validate data assigned to properties and the XML attributes they map to. The
following lists all of the validator attributes within the System.Configuration
namespace:

  • <a title="MSDN Documentation for the CallBackValidatorAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.callbackvalidatorattribute.aspx"
    target=”_blank”>CallbackValidatorAttribute ñ Provides an association between
    a <a title="MSDN Documentation for the CallbackValidator class." href="http://msdn.microsoft.com/en-us/library/system.configuration.callbackvalidator.aspx"
    target=”_blank”>CallbackValidator object and the code to validate ñ allows
    dynamic validation for a configuration value.
  • <a title="MSDN Documentation for the IntegerValidatorAttribute class" href="http://msdn.microsoft.com/en-us/library/system.configuration.integervalidatorattribute.aspx"
    target=”_blank”>IntegerValidatorAttribute ñ Validates using an <a title="MSDN Documentation for the IntegerValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.integervalidatorattribute.aspx”
    target=”_blank”>IntegerValidator object to determine if the configuration
    value falls within or outside a specific range.
  • <a title="MSDN Documentation for the LongValidatorAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.longvalidatorattribute.aspx"
    target=”_blank”>LongValidatorAttribute ñ Validates using a <a title="MSDN Documentation for the LongValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.longvalidator.aspx”
    target=”_blank”>LongValidator object to determine if the configuration value
    falls within or outside a specific range.
  • <a title="MSDN Documentation for the PositiveTimeSpanValidatorAttribute class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.positivetimespanvalidatorattribute.aspx”
    target=”_blank”>PositiveTimeSpanValidatorAttribute ñ Validates using a <a title="MSDN Documentation for the PositiveTimeSpanValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.positivetimespanvalidator.aspx”
    target=”_blank”>PositiveTimeSpanValidator object for positive TimeSpan configuration
    values.
  • <a title="MSDN Documentation for the RegexStringValidatorAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.regexstringvalidatorattribute.aspx"
    target=”_blank”>RegexStringValidatorAttribute ñ Validates using a <a title="MSDN Documentation for the RegexStringValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.regexstringvalidator.aspx”
    target=”_blank”>RegexStringValidator object to determine if the configuration
    value adheres to the the regular expression.
  • <a title="MSDN Documentation for the StringValidatorAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.stringvalidatorattribute.aspx"
    target=”_blank”>StringValidatorAttribute ñ Validates using a <a title="MSDN Documetation for the StringValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.stringvalidator.aspx”
    target=”_blank”>StringValidator object to ensure the configuration value
    meets certain criteria ñ such as string length and invalid characters.
  • <a title="MSDN Documentation for the SubclassTypeValidatorAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.subclasstypevalidatorattribute.aspx"
    target=”_blank”>SubclassTypeValidatorAttribute ñ Validates using a <a title="MSDN Documentation for the SubclassTypeValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.subclasstypevalidator.aspx”
    target=”_blank”>SubclassTypeValidator object to determine if the configuration
    value derives of a given type.
  • <a title="MSDN Documentation for the TimeSpanValidatorAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.timespanvalidatorattribute.aspx"
    target=”_blank”>TimeSpanValidatorAttribute ñ Validates using a <a title="MSDN Documentation for the TimeSpanValidator class."
    href=”http://msdn.microsoft.com/en-us/library/system.configuration.timespanvalidator.aspx”
    target=”_blank”>TimeSpanValidator object to determine if the configuration
    value is falls within or outside a specific range.

With the exception of the CallbackValidatorAttribute, you do not have to create
corresponding validator objects to use in conjunction with the validator attributes.
The .NET runtime creates the appropriate validator objects for you, and the attributes
contain the needed parameters to configure the validator objects.

This small bit of code is all that is required to programmatically represent individual
<add/> elements. The next step is to write a class that represents the <feeds/>
element.

Writing an Element Collection Class

The XML representation of the <feeds/> element is that of a collection of
feed elements. Likewise, the programmatic representation of the <feeds/> element
is a collection of FeedElement objects. This class, called FeedElementCollection,
derives from the abstract ConfigurationElementCollection class.

The ConfigurationElementCollection class contains several members, but only two
are marked as abstract. Thus, the simplest ConfigurationElementCollection implementation
has two methods:

  • CreateNewElement() ñ Creates a new ConfigurationElement object (FeedElement in this
    case).
  • GetElementKey() ñ Gets the element key for a specified configuration element (the
    Name property of FeedElement objects in this case).

With that in mind, view the complete code for the FeedElementCollection class below:

[ConfigurationCollection(typeof(FeedElement))]
public class FeedElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new FeedElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((FeedElement)element).Name;
    }
}

A <a title="MSDN Documentation for the ConfigurationCollectionAttribute class." href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx"
target=”_blank”>ConfigurationCollectionAttribute decorates this collection
class. The first parameter to the attribute is a Type object ñ the type of the items
the collection contains. In this case, it’s the FeedElement type. After the type
parameter are several named parameters you can pass to the attribute. These are
listed below:

  • AddItemName ñ Sets the name of the <add/> configuration element. For example,
    setting this as "feed" would require the <add/> elements in the
    configuration to be changed to <feed/>.
  • ClearItemsName ñ Sets the name of the <clear/> configuration element (used
    to clear all items from the collection).
  • RemoveItemName ñ Sets the name for the <remove/> configuration element (used
    to remove an item from the collection).

Leaving these named parameters blank defaults them to <add/>, <clear/>,
<remove/>.

Writing the FeedRetreiverSection Class

The final class, called FeedRetrieverSection, derives from ConfigurationSection
and represents the <feedRetriever/> element. This is the simplest class of
the configuration classes, as the only requirement it must meet is to provide programmatic
access to the <feeds/> element (the FeedElementCollection).

public class FeedRetrieverSection : ConfigurationSection
{
    [ConfigurationProperty("feeds", IsDefaultCollection = true)]
    public FeedElementCollection Feeds
    {
        get { return (FeedElementCollection)this["feeds"]; }
        set { this["feeds"] = value; }
    }
}

It’s one property, of type FeedElementCollection and called Feeds, is decorated
with a ConfigurationPropertyAttribute ñ mapping it to the <feeds/> element.

Modifying web.config

With the configuration handler complete, you can add the appropriate elements to
web.config. The <feedRetriever/> section can go anywhere in the file as long
as itís a direct descendent of the root element (the <configuration/> element).
Placing it within another configuration section results in an error.

The next step is adding a <section/> child element to <configSections/>.
The <section/> element has two attributes of interest:

  • name ñ The name of the configuration section element. In this case, name is feedRetriever.
  • type ñ The qualified name of the class associated with the section, and if necessary,
    the name of the assembly the class resides in. In this case, the qualified name
    is FeedRetriever.Configuration.FeedRetrieverSection. If it resides in a separate
    assembly, the type attribute would have a value of "FeedRetriever.Configuration.FeedRetrieverSection,
    <assemblyName>", where <assemblyName> is the name of the assembly
    without the angle brackets.

The following <section/> element is what you add to a web.config file, under
<configSections/>, when the configuration classes do not reside in a separate
assembly (as is the case in the code download):

<section name="feedRetriever" type="FeedRetriever.Configuration.FeedRetrieverSection"/>

Now your application is properly configured to use the FeedRetrieverSection, FeedElementCollection,
and FeedElement classes to grant you programmatic access to the custom settings
contained within the <feedRetriever/> configuration section in web.config.
So how do you access these settings from within your code?

Accessing Configuration Data from Code

The System.Configuration namespace contains a static class called ConfigurationManager.
If you use the <connectionStrings/> section to house your connection strings,
you are at least familiar with ConfigurationManager. It has a method called GetSection(),
which accepts a string containing the name of the configuration section to retrieve.
The following code demonstrates this (assume using System.Configuration is at the
top of the code file):

FeedRetrieverSection config = ConfigurationManager.GetSection("feedRetriever") as FeedRetrieverSection;

The GetSection() method returns a value of type Object, so it must be cast to whatever
type the handler is for that section. This code retrieves the section named feedRetriever
and casts the result as FeedRetrieverSection. Once you have the object, you can
start accessing configuration data programmatically.

To give you an idea of how configuration settings can be used within your component
or application, the following code is a very basic implementation of the FeedRetriever
component.

public class FeedRetriever
{
    public static FeedRetrieverSection _Config =
        ConfigurationManager.GetSection("feedRetriever") as FeedRetrieverSection;


    public static void GetFeeds()
    {
        foreach (FeedElement feedEl in _Config.Feeds)
        {
            // make request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(feedEl.Url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string feedData = String.Empty;

                using (StreamReader reader =
                             new StreamReader(response.GetResponseStream()))
                {
                    feedData = reader.ReadToEnd();
                }

                if (feedEl.Cache)
                {
                    // filename of cache file
                    string filename = String.Format("{0}_{1}.xml",
                                            feedEl.Name, DateTime.Now.Ticks);

                    // cache file
                    using (StreamWriter writer =
                             new StreamWriter(@"C:\" + filename))
                    {
                        writer.Write(feedData);
                    }
                }
            }
        }
    }
}

First, a static variable called _Config, of type FeedRetreiverSection, is declared
and assigned a value by calling ConfigurationManager.GetSection(). Making the variable
static is a design choice. By doing so, all members of the class, either instance
or static, would have access to the configuration settings without having to make
multiple calls to GetSection().

Once you retrieve the section handler with GetSection(), you have complete access
to objects created from your handler classes. The first line of GetFeeds() is a
foreach loop that loops through all FeedElement objects contained with the FeedElementCollection
object returned by the Feeds property. This gives you direct access to those FeedElement
objects ñ making it easy to access each feed’s name, URL, and cache settings.

During each iteration of the loop, the method makes a request using the FeedElement
objectís Url property. If the request results in a success, the feedís data is retrieved
and stored in the feedData variable. Then the code checks the FeedElement objectís
Cache property to determine whether or not to cache the feed. Caching the the feed
involves constructing a filename by using the FeedElement objectís Name property
and the current date and time. Then a StreamWriter object creates the file and writes
the feedís data to it.

As you can see, using the configuration section handler classes is key to retrieving
and using custom settings residing in web.config. It certainly requires more time
and effort from you, but it definitely makes your application or component much
easier to configure for yourself and other developers.

Sell your .NET Components on CodeCanyon!

Did you know that we have a .NET category on CodeCanyon. If you’re a skilled .NET dev, why not sell your scripts/components/controls as an author, and earn 40-70% of every sale?



Inspiration: Wonderful Watercolor Websites

Inspiration: Wonderful Watercolor Websites

This article showcases 30+ stunning web designs that make use of the incredible watercolor effect. The showcase is followed up with a small selection of links sharing a few tutorials and watercolor textures and brushes that you can use in your own designs.

Viget Inspire

Viget Inspire is one of the most recognized pieces of watercolor-style web design to date; there aren’t many web designers who haven’t seen it! The style is absolutely stunning, and the combination of the watercolored background and digital foreground and typography mixes incredibly well together.

Deborah Cavenaugh

Web Designer Wall

Web Designer Wall is yet another fantastic web design that is well known for its use of watercolor effects. The stunning watercolored patterns and the whole hand-made feel of the site makes it visually appealing, especially for their target audience: the creative industry.

Toby Powell

Boompa Shop

Boompa Shop have merged modern web design, such as the minimalistic footer, with some great watercolored “doodles” to create a beautiful and very unique effect for the web-based shop design.

Agami Creative

Corvus Design Studio

Corvus Design Studio have used a similar layout style to those typically used in portfolio designs, however instead of keeping it simple and plain to draw attention to their work, they’ve made the portfolio itself a piece of art, which is probably more than enough to persuade any customer to choose them for their latest project.

The Black Keys

Erguvan Platin Evleri

Erguvan Platin Evleri is one of the first to combine two popular trends in the web design industry: abstract watercolor effects and three-dimensional models. In this case the styles work very well together and are pleasing to look at; let’s hope we see more like this!

Davide Savelli

Colour of Air

Colour of Air is the first website in this showcase that uses very subtle watercolor in their design. To bring the content area below the header to life, they have used a low-opacity watercolor texture beneath the header and under the different article areas. The use of rendered noise in the design combined with subtle watercolor works great.

Sergio Design Trends

Sunrise Design

You don’t see vivid watercolor effects very often, mainly because it is quite difficult to pull off. Sunrise Design, however, pull off the effect very well, using bright greens and yellows in the background of their site design to create a happy and joyful feel.

Big Cartel

Volkswagen Escape

There are some huge and very well known companies making the most of the watercolor trend, too, such as the ever-popular Volkswagen car brand. They use a subtle, washed-out watercolor landscape in the background of their web design.

The Croquis

Saint Charles Maryland

Saint Charles Maryland, like several others in this showcase, used a light watercolor wash in the background of their design. This time, however, it is being used in the main content section of the design instead of the main background image. It’s an interesting concept that is pulled off well and goes with their corporate image.

Deep Roots and Wide Wings

Toggle

Toggle is another company that is well known in the creative industry for its fantastic use of watercolor in their website design. Unlike others, the watercolor effect seems to be randomly placed in the center of the background, rather than being used to produce a full background pattern or image (such as a landscape) in most of the other designs. It adds a great “oomph” to the site and brings out the lovely blue color scheme that has been used in the design.

Small White Bear

Brad Candullo

Brad Candullo uses watercolor in his portfolio design to add a little extra something to the background of his header, mainly to help draw attention to his website’s logo. The use of watercolor being used with so many other textures such as subtle grunge and wood is pulled off well and looks great!

Five Points Interactive

4PSD

4PSD is one of the most minimalistic designs in this showcase, simply making use of a light watercolor wash to separate the header area from the rest of the design. The colors go well with the site’s overall color scheme, and the use of whitespace only makes the watercolor effect look better!

K4 Laboratory

Binocle

Binocle is another site that uses a vivid watercolor effect in their design, this time using a very hot pink/red that slowly merges off to a deep pink/purple and magically transforms into a million birds. The effect is great and it really helps bring out the true power of the pink color used in the rest of the design.

Happy Cog

Imaginary Moments

The use of watercolor in this website design is superb! It’s very unique compared to the rest of the designs in this showcase, and is one of my personal favorites. I love how it has been merged with various other images and textures, and just the overall feel of the site.

Lebloe

Weberica

Weberica is possibly the grungiest watercolor styled web design in the showcase. It’s dark, olive green colors bring out the lovely gradient effect used in the logo, and those pink flowers help to bring out the small amount of red typography that is used in the rest of the design.

Football Made In Africa

Tylor J. Reimer

Tylor J. Reimer’s portfolio design is so simple yet so beautiful. The bright splashed watercolor effect combined with the hand-sketched dog is wonderful, and the low opacity neutral content background help to separate the illustration from the website’s content.

Helpful Resources

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



Quick Tip: Learning jQuery 1.4’s $.proxy

Quick Tip: Learning jQuery 1.4’s $.proxy

One of my favorite new features in jQuery 1.4 is the new $.proxy method. It allows us force a particular context when calling a method. In JavaScript, there can be times when it’s difficult to hold on to the this keyword. For example, when it’s bound to some event handler, this now refers to the target of the handler, rather than your desired object.

If this sounds a bit confusing, don’t worry; today’s four-minute video quick tip should clear things up.


// Create an object.
var obj = {
        // this = obj
	somevar : 'some value',

	doSomething : function() {
		alert(this.somevar);
	}
};

// When bound to an event handler, this will
// refer to the target of the handler, or the div - not obj.
$('div').click(obj.doSomething); // undefined. 

// With $.proxy, we pass two parameters.
// 1. The method to call.
// 2. The context.
// In this case, we're forcing obj to once again be equal to this.
$('div').click( $.proxy(obj.doSomething, obj) ); // some value

Be sure to refer to the jQuery API for more information on $.proxy!



How to Build and Enhance a 3-Level Navigation Menu

How to Build and Enhance a 3-Level Navigation Menu

Perhaps more than any other topic, I’m most often contacted about how to build cross-browser navigation menus. Understandably, the reason is because every web designer has built one at some point, if not during every project! Nonetheless, it can absolutely be a tricky task. In this video tutorial, I’ll teach you how to build an attractive cross-browser navigation menu; notable features include CSS3 gradients, multiple sub-menus, and jQuery animations.


Other Viewing Options

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



CodeIgniter from Scratch: The Calendar Library

CodeIgniter from Scratch: The Calendar Library

In this tenth episode of the CodeIgniter From Scratch screencast series, we will be exploring the Calendar library. We are also going to utilize the database class and jQuery AJAX. I will show you how to build a simple and CSS-styled calendar page, which will have the ability to store and display content for each day.

Final Example

Catch Up

Day 10: The Calendar Library

Other Viewing Options



Design a Prettier Web Form with CSS 3

Design a Prettier Web Form with CSS 3

Thanks to advanced CSS properties, such as gradients and shadows, it’s now quite easy to turn a dull web form into something beautiful – with minimal effort. I’ll show you how in today’s tutorial!


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.

Our Final Product

Subtle background gradients give depth to the fields while shadows lift them from the page. Even more impressive is that this is done without any images at all.

By following this tutorial you will not only end up with a lightweight and beautiful form, you’ll also learn and understand new CSS3 techniques, such as box-shadow, gradients, opaque colors, and rounded corners.

CSS3?

CSS3 is the next generation of CSS that is currently under development, but that doesn’t stop browsers from already implementing most of the prominent features.

Full browser support:

Opera have support for CSS3 (except background gradients) in their next version (10.50 Beta).

Internet Explorer will have full CSS3 support with version 9.

The things you can do with CSS3 (shadows, gradients, round corners, animations, etc) all serve a purpose of creating beautiful effects without having to integrate images or scripts, resulting in quicker loading times.

Step 1: The HTML

Before we begin styling we need something to style, so here is the form.

<form class="form">

	<p class="name">
		<input type="text" name="name" id="name" />
		<label for="name">Name</label>
	</p>

	<p class="email">
		<input type="text" name="email" id="email" />
		<label for="email">E-mail</label>
	</p>

	<p class="web">
		<input type="text" name="web" id="web" />
		<label for="web">Website</label>
	</p>

	<p class="text">
		<textarea name="text"></textarea>
	</p>

	<p class="submit">
		<input type="submit" value="Send" />
	</p>

</form>

Each field is inside a paragraph with its own class, and the three first fields have a label explaining their use.

How does it look without any styling?

Functional, but dull. Let’s start pimping out this form.

Step 2: Basic Styling

Before we dive into the CSS3 techniques we need to create a basic layout for browsers that don’t yet support CSS3.

input, textarea {
	padding: 9px;
	border: solid 1px #E5E5E5;
	outline: 0;
	font: normal 13px/100% Verdana, Tahoma, sans-serif;
	width: 200px;
	background: #FFFFFF;
	}

textarea {
	width: 400px;
	max-width: 400px;
	height: 150px;
	line-height: 150%;
	}

input:hover, textarea:hover,
input:focus, textarea:focus {
	border-color: #C9C9C9;
	}

.form label {
	margin-left: 10px;
	color: #999999;
	}

.submit input {
	width: auto;
	padding: 9px 15px;
	background: #617798;
	border: 0;
	font-size: 14px;
	color: #FFFFFF;
	}

How does our effort look so far?

Not too bad. Now, let’s begin our enhancements with the more advanced CSS3.

Step 3: Box-shadow

Box-shadow does exactly what it sounds like: creates a shadow around a box.

The syntax for box-shadow is fairly simple:

box-shadow: <color> <horizontal offset> <vertical offset> <blur>;

Horizontal offset is the placement of the shadow from left to right. If you set it to “2px” the shadow will be 2 pixels to the right. Vertical offset is the same but up/down.

Blur is simply the amount of blur the shadow will have, where 0 is minimum.

This is how our box-shadow will look like:

input, textarea {
	box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	}

Here we have three lines that look similar.

  • box-shadow is pure CSS3 and so far only used in Opera.
  • -webkit-box-shadow is for browsers using the Webkit engine, like Chrome and Safari.
  • -moz-box-shadow is for browsers using Mozilla’s Gecko engine, like Firefox, Camino, Flock, and SeaMonkey.

Until CSS3 becomes the standard, you have to use all three methods. Internet Explorer has their own weird way of doing things, and although it’s capable of making a shadow it will not look the way we want it. 3

You might notice that there was no normal RGB color used, this is because we’re using two CSS3 techniques on the same line: box-shadow and rgba.

RGBA (Red Green Blue Alpha) is, simply put, color with opacity.

The syntax for rgba is this:

rgba(<red>,<green>,<blue>,<opacity>);

It’s perfectly fine to use a light grey for the shadow’s color, but if you are using any other background than white it will look strange. An opaque black on the other hand will work well no matter what background.

So our box-shadow is black with 10% (0.1) opacity, no horizontal and vertical offset, and with a blur of 8 pixels. It will look like this:

The keyword here is subtlety. If we apply too much shadow, it will look ugly; if we apply too little, it won’t have an effect. Basically, we don’t want anyone to notice the shadow, but still have it lift the fields from the page.

Step 4: Background Gradient

While the box-shadow syntax is easy to grasp, gradients are trickier. With CSS3 gradients, you can create some amazing shapes — from dart boards to rainbows — so as you can imagine it has a more complex syntax. Thankfully, we don’t need to code a rainbow today; we just need a straight linear gradient.

Syntax for Webkit:

-webkit-gradient( linear, <start>, <end>, from(<color>), to(<color>) )

Syntax for Gecko:

-moz-linear-gradient(<start> <angle>, <color>, <color>)

As you can see, the methods are quite different, so this will require some explaining.

Webkit gradients require a start point (X and Y), an end point (X and Y), a from-color, and a to-color. The angle is determined by where start and end are, and the gradient will be colored with the “from(color)” fading to “to(color)”.

Gecko gradients, on the other hand, require only a start point (Y), and at least two colors. If you want a gradient going from top to bottom (90deg) you don’t need to assign an angle.

So to get a simple linear gradient from top to bottom – black to white – we would do like this:

background: -webkit-gradient(linear, left top, left bottom, from(#000000), to(#FFFFFF));
background: -moz-linear-gradient(top, #000000, #FFFFFF);

And it would appear like this:

(I will continue to use the black color for demonstration; at the end, I’ll switch to the real color we will be using for the form.)

Now that we have the basics out of the way, we can start making the form look how we want. The first thing we want to do is limit the height of the gradient so that it looks the same for both input fields and textarea; otherwise the gradient would fill the entire height, like this:

This is how we limit the background gradient to 25px in Webkit and Firefox:

input, textarea {
	background: -webkit-gradient(linear, left top, left 25, from(#000000), to(#FFFFFF));
	background: -moz-linear-gradient(top, #000000, #FFFFFF 25px);
	}

For Webkit, instead of setting the end point to “left bottom,” we set it to “left 25″, indicating it will end 25 pixels from the top.

For Gecko, we do the same thing by simply adding a “25px” value to the end color.

And the result is:

The second thing we want to do is create a thin white line at the top of the gradient, to give the subtle visual impression that the field is raised. How important can a single pixel be? Take a look at this article: Adding Depth with Pixel Perfect Line Work.

To create this, we’ll need three points in the gradient. In the previous example, our gradient had two points: top and bottom (black→white). Here, we’ll add an additional point in between them (white→black→white).

To illustrate:

How do we do this?

input, textarea {
	background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #000000), to(#FFFFFF));
	background: -moz-linear-gradient(top, #FFFFFF, #000000 1px, #FFFFFF 25px);
	}

In Webkit we use the color-stop function, but unfortunately it doesn’t support values in pixels, only percentage. But thanks to paying attention to math in school we figure that 4% of 25px is 1px.

For Gecko, we simply add a third color between the first two and give it a “1px” value, indicating that it should end 1 pixel from the top.

The thin white line:

Now, let’s change the black color (#000000) to a more fitting light grey (#EEEEEE):

Just some small detail work remains.

First, we’ll create a darker shadow for the fields when the user hovers or selects it:

input:hover, textarea:hover,
input:focus, textarea:focus {
	-webkit-box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
	}

It’s just an increase from 10% to 15%, but what we are after is, once again, subtlety.

The last thing we do is create some rounded corners for the button3 to further make it stand out from the other elements:

.submit input {
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	}

The value is the radius the corners will be rounded by. The standard border-radius is intentionally left out since Opera seems to have some problem with it.

Result:

Step 5: The Other Browsers

Now we just need to take care of the browsers that don’t support CSS3 yet (IE), or only partly does (Opera).

We want the different versions (CSS3 and the normal) to look as similar as possible, and the simplest thing is to go back to the old way: images.

Simply take a screenshot of the beautiful CSS3 form and save a small portion of the gradient as an image.

Next, use it in the input and textarea as a background. As long as the CSS3 gradients comes after the background image, browsers that support CSS3 will ignore the image.

input, textarea {
	background: #FFFFFF url('bg_form.png') left top repeat-x;
	}

And now we are done! Enjoy your form and I hope you have learned something.

Final Preview

Chrome (4.0), Firefox (3.6), Safari (4.0):

Opera (10.50b):

Internet Explorer (8):

Full CSS

input, textarea {
	padding: 9px;
	border: solid 1px #E5E5E5;
	outline: 0;
	font: normal 13px/100% Verdana, Tahoma, sans-serif;
	width: 200px;
	background: #FFFFFF url('bg_form.png') left top repeat-x;
	background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
	background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
	box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	}

textarea {
	width: 400px;
	max-width: 400px;
	height: 150px;
	line-height: 150%;
	}

input:hover, textarea:hover,
input:focus, textarea:focus {
	border-color: #C9C9C9;
	-webkit-box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
	}

.form label {
	margin-left: 10px;
	color: #999999;
	}

.submit input {
	width: auto;
	padding: 9px 15px;
	background: #617798;
	border: 0;
	font-size: 14px;
	color: #FFFFFF;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	}

Conclusion

That’s all there is to it! With minimal effort, and the power of CSS 3, we’ve turned a bland and ordinary form into something beautiful. Thanks so much for reading, and feel free to ask any questions that you might have below.

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