Web Design Basics – Placement and Position

When you’re starting a new design, no matter what your design methodology is, you start with a blank page. There is nothing on the Web page – so the first thing you’ll do is put something up on the page.

But do you think about the placement of those elements or do you just throw them onto the page willy nilly? Good designers don’t allow the position and placement of their designs to occur randomly. They think about:

  • what the element is
  • how the element relates to the page goals
  • where the element fits with the other elements on the page

What is the Element You’re Placing
There are many common elements on a Web page, such as: headlines, navigation, images, textual content, and administrativa. Knowing what an element is helps determine where it should be placed on the page. For example, you typically wouldn’t put a Web page headline at the very bottom of the page. Navigation is usually found on the left or at the top, and administrativa is most commonly found at the bottom.

How Does the Element Relate to the Page Goals
Knowing your goals and the goals for the page are key to placement. That’s why ads are found in similar places on Web pages. If the goal is to get people to click on them or notice them, then placing them in locations where historically people look and click helsp them to meet their goals.

Where are the Other Elements on the Page
In some ways this appears to be the most obvious part of design – after all if you already have a logo in the upper left, you’re not going to place content on top of it. But you also need to think about the context of your positions. Placing an ad block in the middle of a text block implies a sense of connection between the two elements. Placing a horizontal line after a headline or by-line can create a sense of disconnect between the title or by-line and the content.

Where you Place Your Elements Can Make a Difference

As they say in real estate, there are three important rules: “Location. Location. Location.” If the Mona Lisa were stored in my aunt’s garage, it wouldn’t have the effect on people that it does hanging in the Louvre. It’s still the same painting, but if it were sitting next to cans of old paint, a dirty lawn mower, and a dust covered junker car it takes on the aspect of its surroundings.

Now, I don’t think that most people have a “ghetto” location on their Web pages, but effective placement provides the visual hierarchy and structure to your Web page. If you can engage your customers through an interesting and compelling design, you’ve done half the work.

Variety is the Spice of Life

One of the easiest design techniques is to center elements on the page. And many beginning designers start with that as their goal – all their design elements start in the middle, usually horizontally, but sometimes vertically as well. Centering appeals to many people because it’s easy. You know you’ve “done it right” because half the page elements are on one side of the screen and the other half is on the other.

But centering is boring. Centering things makes them look very flat on the screen and there is nothing for your eye to catch and hang onto. Centering is very rare in nature. In fact, even things that appear to be centered, like leaves (see picture) have small imperfections that lead the eye.

The dot in the image has been positioned so that it’s completely not centered. Each of the horizontal and vertical measurements from the edges of the page are different. You can see this on a Web page, too. By playing with the placement of the dot (and by extension, other elements of a Web page) you provide variety to your designs. You can apply this to more than one element on the page by spacing them unequally from each other as well as the page edges. Here’s an example of unequal spacing with two dots.

Find the Points of Interest on Your Page

Points of interest are the focal points of a design – the places where your eye is drawn to. By changing the spacing around those points of interest you can affect how those items are viewed on the page.

For example, an image might be the focal point of your Web page. You could choose to center the image on the page, but that’s boring and flat. Instead look at the other elements on the page and change the margins around your image to create a design that heightens the interest in that picture.

On this sample page, I placed three elements: a headline, a photo, and a caption. I could choose to center all the elements, but it’s a boring layout and there is no clear visual hierarchy. Your eye is drawn to the image because it’s an image, not because of the position it has in the layout.

By just making a couple small changes to the position of the elements and the margins around the image, the resulting layout is more visually appealing and the eye is drawn from the headline, through the photo, to the caption. Because the spacing between the headline and the image is different from the caption and image space, you get a sense that the caption belongs with the image. I could add more photos to this page and it would be clear they were about Shasta, but the captions would go with each image separately.

More Design Positioning Information

The dot image is not my idea – I found it in a great design basics book called Design Basics Index by Jim Krause (compare prices).

Leave a comment »

How to Build a Website

How to Build a Website Step 1 – Hosting:

Hosting is where you put your website and all the Web pages. While it’s possible to build a website on your personal computer and never move it online, it’s somewhat pointless. No one but you will ever be able to see it. So the first thing you’ll want to do is find a Web hosting provider.

There are several types of Web hosting options you can choose from:

  • Free Web hosts
  • Standard Web hosting
  • Dedicated, Virtual, and Shared Hosting
  • Colocation

Most people gravitate to free Web hosting without too much thought, but there can be drawbacks to free hosting. You don’t always get as much space, you might be required to run their ads on your site, or there may be bandwidth limits. Be sure to read all the fine print before you put your website on a free Web host. I recommend using free hosting providers for testing Web pages and for personal pages.

  • Find a Web Hosting Provider – links to other sites for help finding a good host
  • Web Hosting Reviews – find out what other users think
  • Web Hosting Profiles – overviews of several hosting providers
How to Build a Website Step 2 – Do You Need a Domain Name?:

You don’t need a domain name to put up a website. You can put up a site on free hosting or even paid hosting plans without a domain name. A domain name provides extra branding for your site and makes it easier for people to remember the URL. But domain names cost money, typically between $8 and $35 a year.

  • Get a URL that People can Find
  • How to Buy a Domain Name with Network Solutions
  • How to Register a Web Site Domain – Video
How to Build a Website Step 3 – Plan Your Website:

Once you’ve gotten a domain and decided on your URL, you can start planning your site. You need to decide:

  • Type of site – Most websites are either news/information, product, or reference sites. As such they each have a slightly different focus.
  • Navigation – The navigation affects the information architecture of your site.
  • Content – Content is the actual pages you’ll be building.

If you can recognize page types, you’ll be able to recognize what types of pages you need for your site. Play the Web Page Types game.

How to Build a Website Step 4 – Build Your Website Page by Page:

Building a website requires that you work on one page at a time. To build your site you should be familiar with:

  • Design Basics – The elements of good design and and how to use it on websites.
  • Learning HTML – HTML is the building block of a Web page. While it’s not absolutely required, you’ll do better if you learn HTML than if you don’t.
  • Learning CSS – CSS is the building block of how pages look. And learning CSS will make it easier for you to change your site’s look when you need to.
  • Web Page Editors – Finding the perfect editor for your needs will help you learn design, HTML, and CSS.
How to Build a Website Step 5 – Publish Your Website:

Publishing your website is a matter of getting the pages you created in step 4 up to the hosting provider you set up in step 1. You can do this with either the tools that come with your hosting service or with FTP clients. Knowing which you can use depends upon your hosting provider. Contact them if you are not sure.

  • How to Upload
  • Best FTP Clients for Windows
  • Best FTP Clients for Macintosh
How to Build a Website Step 6 – Promote Your Website:

The easiest way to promote your website is through search engine optimization or SEO. You build your Web content so that it ranks well in search engines. This can be very difficult, but it is inexpensive and can result in good results if you work at it.

Other ways to promote your site include: word of mouth, email, and advertising. You should include your URL on all professional correspondence and whenever it makes sense in personal messages. I put my URL in my email signature along with my email address.

  • Improve Your Page Views – With More Hits
  • Boosting Your Hits
  • Create a Great Home Page
  • Web Marketing Articles
How to Build a Website Step 7 – Maintain Your Website:

Maintenance can be the most boring part of website design, but in order to keep your site going well and looking good, you need to do it. Testing your site as you’re building it and then after it’s been live for a while is important. And you should also work on content development on a regular basis.

Leave a comment »

ASP : SSI Another Way

This is another SSI tutorial written by a friend, it shows another way of looking at SSI and also shows you some new tricks and tips.

Server Side Include (SSI) files are a great way to simplify management of a web site. If you have a 100-page site and all 100 pages have a left-side navigation menu, why have the menu written 100 times? What if one of the links on the menu changes? You would have to change the link 100 times. A much more efficient way to manage this is to create a menu file and include it on all of the pages. All you have to do then is change the link in your menu file, and all of the other pages will fall in line.

All you need to use SSI is a web server that supports SSI. Virtually all the current popular web servers – Apache and IIS included – support SSI.

Here’s what an old index.html page might look like:

<table>
<tr>
<td>
<table>
<tr><td><a href=”/img_articles/9123/link1.shtml”>Link 1</a></td></tr>
<tr><td><a href=”/img_articles/9123/link2.shtml”>Link 2</a></td></tr>
<tr><td><a href=”/img_articles/9123/link3.shtml”>Link 3</a></td></tr>
</table>
</td>
<td>
Content goes here.
</td>
</tr>
</table>

Step 1 would be to take the center table out and save it as menu.htm.

<table>
<tr><td><a href=”/img_articles/9123/link1.shtml”>Link 1</a></td></tr>
<tr><td><a href=”/img_articles/9123/link2.shtml”>Link 2</a></td></tr>
<tr><td><a href=”/img_articles/9123/link3.shtml”>Link 3</a></td></tr>
</table>

And change your main page to:

<table>
<tr>
<td>
<!–#include file=”menu.htm”–>
</td>
<td>
Content goes here.
</td>
</tr>
</table>

Save it as index.shtml

Simple enough, right? Well, where it gets more complex is when you throw subdirectories into the mix. Suppose link1.shtml was now in a directory called subdir1.

link2.shtml was inside of subdir1/subdir2, and link3.shtml was in subdir1/subdir2/subdir3 but we still want to use the navigation menu. We would change the menu.htm file to:

<table>
<tr><td><a href=”/img_articles/9123/subdir1/link1.shtml”>Link 1</a></td></tr>
<tr><td><a href=”/img_articles/9123/subdir1/subdir2/link2.shtml”>Link 2</a></td>
</tr>
<tr><td><a href=”/img_articles/9123/subdir1/subdir2/subdir3/link3.shtml”>Link 3</a>
</td></tr>
</table>

Plus, we’d have to change the include statement to:

<!–#include file=”../menu.htm”–>

That will work, but now suppose we want to go to Link 2. It is in subdir2 underneath subdir1, so when we click on Link 2, we’d get a 404 – Page Not Found – error. So the question is, how can we avoid all these “dotdot” issues?

First, create a new subdirectory called inc and place your menu.htm file inside of it. Then instead of the previous include statement, use:

<!–#include virtual=”inc/menu.htm”–>

What virtual does is tell the server to go back to the root directory first, then pull the specified file, including any subdirectories. It makes the include statement independent of the subdirectory it being called in. So we could be inside of subdir1/subdir2/subdir3/subir4/subdir5, and by using #include virtual, it will still pull menu.htm out of the inc directory off of the root.

So that solves our first problem of having to keep track of all of the “dotdot”s in our include statement. Now we have to make sure we’re not dependent on the current place of the directory structure to load the correct page. The simple solution is to stop using relative links, and use the “/” character. It’s similar to using include virtual as it tells the server you want to back to the root directory first. So menu.htm would now look like:

<table>
<tr><td><a href=”/img_articles/9123//subdir1/link1.shtml”>Link 1</a></td></tr>
<tr><td><a href=”/img_articles/9123//subdir1/subdir2/link2.shtml”>Link 2</a></td>
</tr>
<tr><td><a href=”/img_articles/9123//subdir1/subdir2/subdir3/link3.shtml”>Link 3</a>
</td></tr>
</table>

And your done!

Leave a comment »

ASP : Server Side Includes

This tutorial was written by one of the great guys at HTMLForums. I read through this tutorial myself and found it to be very useful and easy to understand. Once I read through his tutorial and did a few examples for myself I sent Entimp an e-mail to ask if he wouldn’t mind me sharing it on this site, he kindly granted me the permission to use his tutorial and here it is, for all of you out there that wish to learn something about ASP.

“Server Side Includes” will be written in short as SSI for the rest of this tutorial.

It doesn’t matter if you are a HTML pro moving on to XHTML or a complete beginner to writing pages for the internet. The uses of SSI are many fold and work wonders for dynamic or static pages. For the purposes of this tutorial I will be dealing with static pages only. If you want to progress onto dealing with SSI in dynamic pages then you will have to follow your own nose. This tutorial will be long enough without dealing with dynamic page content.

So what do you need?

A working knowledge of HTML. How to link files through various levels of a given directory structure (ideally). A server that will provide server side permissions. In this case ASP. I am writing this for ASP users simply as that is where my experience resides. I am sure users of PHP will be able to pick the gist of this up and transfer the inherent contents to their choice of server side platform.

To transfer this knowledge to you with some ease we are going to take a generic static web site and show how it could benefit from SSI.

We shall call this fictional website “Biology for Beginners”. Biology for Beginners is a web site that provides resources for students of … guess what … Biology. Although it can provide an awful lot of information in different content sections we are only going to give it 4 for the purposes of this tutorial.

These areas are: Famous Biologists, Biological Links, Journal Articles and Biological Photo Gallery.

The site has a typical layout. A header area for the site logo with a content area below that with navigation on the left and finally at the bottom a footer for other information.

A link clicked in the navigation area would open in the content area. This could be done in 3 common ways. With an Iframe (inline frame), a HTML frameset, or as a new HTML document with navigation, header and footer as well. The HTML might look something like this (non frame version) :

<html>
<head>
</head>
<body>
<table width=”100%”>
<tr>
<td colspan=”2″>Header Area</td>
</tr>
<tr>
<td width=”25%”>Navigation area</td>
<td width=”75%”>Content Area</td>
</tr>
<tr>
<td colspan=”2″>Footer Area</td>
</tr>
</table>
</body>
</html>

This is obviously very simplified but it serves our purpose. Just pretend it has all the meta tags in there and all the content.

Frames are fine to an extent so why bother with SSI? Good question! Frames do have their problems such as search engines and disability issues. If you want high listings in search engine results these days you have to have content. Some search engines still have issues with reading the framed content. As for writing the new content for individual HTM documents this is time consuming especially if you have to change the format of the page. If you want to give your site a new paint job it can be soul destroying in editing each individual document in your site. This is where SSI comes to your rescue.

The next step is to understand how to use an SSI and how it works.

So what is a server side include?

A server side include is a way of requesting a given piece of information from your server and including it in the displayed web document. The information can be anything you want it to be. Plain text, markup language, scripts etc…

The page we are writing has lots of repeated areas of code and it wouldn’t make sense to write it out time and time again if we could avoid it. For now, Biology for Beginners only has one area that has unrepeated/unique code and that is the content section.

Logically we should try and break down the repeatable sections of code into sensible categories. Biology for Beginners can be broken down into these:

  • Header
  • Navigation content
  • Code for center of table
  • Content
  • Footer

All of the above sections are repeatable sections of code other than the content section. Given that I had all these files pre-created I could publish a web page in seconds bar the content. The code you would write would look something like this:

<!–#include file = “includes/header.asp” –>
<!–#include file = “includes/nav.asp” –>
<!–#include file = “includes/table.asp” –>
<!–#include file = “includes/content_xx.asp” –>
<!–#include file = “includes/footer.asp” –>

Believe it or not that code would display a full and valid web page providing you have all the includes pre-written.

One of the first things you will notice is the extensions to the includes. You could use any of 3 extensions for SSI, being *.txt, *.inc and *.asp. I suggest you only use the *.asp extension and will good enough to tell you why.

To understand why, you need to know how a SSI is served up. This is going to be extremely basic in description. To do this I will compare an ASP page with a HTML page.

HTML page

A fairly basic web page written in HTML can be described as static file… when it is requested the HTML is sent you as it is and your browser defines how it is displayed on the screen. Once the browser has the code only then does it start to get the images. Images are not sent automatically with HTML file requests. It is also the same of HTML rendered via ASP…

ASP page

The ASP server looks at the includes first, builds the HTML from all the separate include files, sends it to your browser pieced together and the browser then requests the images.

An ASP page (Active Server Page) is very different. Any page that runs ASP must have an extension of *.asp rather than *.htm. The include files will also be called *.asp (or *.inc or *.txt). For this tutorial I am going to suggest you use the *.asp extension and not the*.inc or *.txt ones. You will find it a little safer to use the *.asp extension due to the way a server responds to files with *.asp. This boils down to a file called ASP.DLL… suffice to say I wont explain anymore other than that you for simple includes you don’t need to know anymore.

By giving the document an ASP extension you change the way a server deals with it. When you request an ASP file the server doesn’t send it to you but has a read of it first. It needs to read it first to understand what must be done to , where all the includes can be found and only then put the front end code together before sending it to you.

With our example of SSI’s you are telling the server to act like a warehouse. In essence it reads the code and gets the shopping list together… one of these, two of them and a few of these and then follows instructions to put it together. Only then does it send it to you in the correct order. When you view the source you will not see the includes but the code that it put together like a jigsaw from the individual includes.

Thus if you give your documents an extension of HTM or HTML the server would not know that it needs to read it first and then act on what it discovers. This doesn’t mean that you can’t write a normal HTML file and call it ASP. The server will still read it and discover that it has nothing to act on and just serve all the HTML to the browser. This should point out to you that no matter what ever is in your individual ASP includes your browser still understands HTML and not ASP. ASP is not a language but a way of serving the language. So remember what ever pieces of the jigsaw you use they must end up as valid HTML when they reach the users browser.

Here is the plain html we are going to cut up

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html lang=”en”>

<head>
<title>Biology for Beginners</title>
<meta http-equiv=”Content-Type” content=”text/html;
charset=ISO-8859-1″>
<meta name=”title” content=”Biology for Beginners… a new biology resource”>
<meta name=”description” content=”Biological resources.”>
<meta name=”keywords” content=”biology, science, evolution, genetics”>
<meat http-equiv=”charset” content=”ISO-8859-1″>
</head>

<body>
<table width=”98%” border=”0″ cellspacing=”0″ cellpadding=”0″ align=”center”>
<tr>
<td colspan=”2″>
<img src=”/img_articles/9124/image_files/header.jpg” alt=”Page logo”>
</td>
</tr>
<tr valign=”top”>
<td width=”200″ align=”left” valign=”top”>

Navigation<br>
<br>
<a href=”/img_articles/9124/fambiologists/list.asp”>Famous Biologists</a><br>
<a href=”/img_articles/9124/links/links.asp”>Biology Links</a><br>
<a href=”/img_articles/9124/j_articles.asp”>Journal Articles</a><br>
<a href=”/img_articles/9124/gallery.asp”>Gallery</a>
</td>
<td>
Content Area
</td>
</tr>
<tr>
<td colspan=”2″>
<td>
</tr>
</table>
</body>
</html>

As you will see the code above is broken into 7 areas, 4 red and 3 blue. The colours don’t mean anything other than to show where I am going to cut these files up to make the individual include files.

Chopping up the code

We need to chop this code up, save it with the correct extensions and then deploy it. It is wise to use names that make sense when you save these files as you are going to repeat the use of them. If you can come up with better names for yours files then credit to you, but these work for me. When saving them create a new folder called ‘includes‘ and save them all there so they are easy to find.

Save this as: meta_and_header.asp

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html lang=”en”>

<head>
<title>Biology for Beginners</title>
<meta http-equiv=”Content-Type” content=”text/html;
charset=ISO-8859-1″>
<meta name=”title” content=”Biology for Newbies… a new biology resource”>
<meta name=”description” content=”Biological resources.”>
<meta name=”keywords” content=”biology, science, evolution, genetics”>
<meat http-equiv=”charset” content=”ISO-8859-1″>
</head>

<body>
<table width=”98%” border=”0″ cellspacing=”0″ cellpadding=”0″
align=”center”>
<tr>
<td colspan=”2″>
<img src=”/img_articles/9124/image_files/header.jpg” alt=”Page logo”>
</td>
</tr>
<tr valign=”top”>
<td width=”200″ align=”left” valign=”top”>

Save this as: nav.asp

Navigation<br>
<br>
<a href=”/img_articles/9124/fambiologists/list.asp”>Famous Biologists</a><br>
<a href=”/img_articles/9124/links/links.asp”>Biology Links</a><br>
<a href=”/img_articles/9124/j_articles.asp”>Journal Articles</a><br>
<a href=”/img_articles/9124/gallery.asp”>Gallery</a>

Save this as: before_content.asp

</td>
<td>

There is no save for the content area, yet anyway. I hope you saw this coming.

Save this as: after_content.asp

</td>
</tr>
<tr>
<td colspan=”2″>

For the footer area there is no code either… yet!

Save this as: end_page.asp

<td>
</tr>
</table>

</body>
</html>

Okey dokey… so we now have the includes we need. These are:

  • meta_and_header.asp
  • nav.asp
  • before_content.asp
  • after_content.asp
  • end_page.asp

You saved these to a folder called ‘includes’ didn’t you? No? Then go do it now!

Back? Good! Then let’s make our fist web page that uses SSI’s. This will be an index page for the very simple website we are creating. Open your design tool of choice… notepad or DreamWeaver for example. Save this file as index.asp, remember the asp extension or the server will not read it before it gets sent.

Now you have a blank document, we need to add some includes. The first one will be ‘meta_and_header.asp‘, and then add the rest. It will look like this:

<!–#include file = “includes/meta_and_header.asp” –>
<!–#include file = “includes/nav.asp” –>
<!–#include file = “includes/before_content.asp” –>
<!–#include file = “includes/after_content.asp” –>
<!–#include file = “includes/end_page.asp” –>

All things being equal, that I lead you down this strange path correctly and you did as I said… the instructions above saved as index.asp will render you a perfectly valid web page. Without the content or footer areas being empty that is.

That isn’t good is it? Well it is to an extent. I now want you save this file as my_template.asp so that when you add content all you need do is refer to this file.

So back to index.asp, open it and add some content of your choice.

<!–#include file = “includes/meta_and_header.asp” –>
<!–#include file = “includes/nav.asp” –>
<!–#include file = “includes/before_content.asp” –>

Shock Horror the content goes here! You would have never worked that out would you! You can add what ever you want, plain text, or normal markup (html), even scripts.

<!–#include file = “includes/after_content.asp” –>

You can do the same here for the footer region… alternativly you can create custom content, save it as an ASP file and serve it as another include. This seems to be awful lot of work for a simple page doesn’t it… well hang in there.

<!–#include file = “includes/end_page.asp” –>

Now create the files:

  • biologists.asp
  • links.asp
  • article.asp
  • gallery.asp

Add the content to the template you made and save it as one of the above. Remember your content can be saved as another include, and not just written into a template page. Remember when writing your links you are directing the anchor at one of the files above and not the individual include files. I hope that makes sense.

Now send all your files to your ASP enabled server, remember you cannot run these to test from your home computer. Once uploaded you should be able to test them.

So there ya go! Hope this helps and puts a few of you on the path of more confusing and screwed up web design.

Leave a comment »

4 Powerful Features of Javascript Programming Language

In the community of web developers and surfers, Javascript is highly popular as client side scripting language for web browsers. In any web application, javascript can be used to implement simple features like rollover of images as well as to make asynchronous requests to server using ajax. Few years back when flash was not so popular, javascript was widely used to add beautiful effects to webpages and is still being used for the same purpose. Let’s take a look at some of the features of this language.

1. Browser support

To access flash content, you need to install flash plugin in your browser. But to use javascript, you don’t have to use any plugin at all. This is because all browsers have accepted javascript as a scripting language for them and provides integrated support for it. All you need to do is to handle some of the tasks that are dependent on DOM (Document Object Model) of different browsers properly.

2. Can be used on client side as well as on server side

As javascript has access to Document object model of browser, you can actually change the structure of web pages at runtime. Due to this, javascript can be used to add different effects to webpages. On the other hand, javascript could be used on the server side as well. For example, in Alfresco which is a popular open source enterprise content management system, javascript is used in creating webscripts. This makes adding custom tasks to alfresco quite simple.

3. Functional programming language

In javascript, function could be assigned to variables just like any other data types. Not only that, but a function can accept another function as a parameter and can also return a function. You can have functions with no name as well. Clearly, this gives you the ability to code in functional programming style.

4. Support for objects

Javascript is an object oriented language. However, the way javascript handles objects and inheritance is bit different from conventional object oriented programming languages like Java. Due to this, javascript supports most of the object oriented concepts while being simple to learn and use.

These are some of the features that give javascript an ability to handle simple as well as complex tasks. Due to this, javascript has remained as the most popular programming language for a long time. It is also a good language for people who want to learn computer programming as it supports object oriented as well as function concepts and to use it, you just need a browser and a text editor.

Leave a comment »

How to Add Flair to your Actions with jQuery

If actions speak louder than words, then in the JavaScript world, effects make actions speak louder still. With jQuery, we can easily add impact to our actions through a set of simple visual effects, and even craft our own, more sophisticated animations.

Inline CSS Modification

Before we jump into the nifty jQuery effects, a quick look at CSS is in order. One way of modifying a document’s appearance is by defining styles for classes in a separate stylesheet and then adding or removing those classes with jQuery. Typically, this is the preferred process for injecting CSS into HTML because it respects the stylesheet’s role in dealing with the presentation of a page. However, there may be times when we need to apply styles that haven’t been, or can’t easily be, defined in a stylesheet. Fortunately, jQuery offers the .css() method for such occasions.

This method acts as both a getter and a setter. To get the value of a style property, we simply pass the name of the property as a string, like .css(‘backgroundColor’). Multi-word properties can be interpreted by jQuery when hyphenated, as they are in CSS notation (background-color), or camel-cased, as they are in DOM notation (backgroundColor). For setting style properties, the .css() method comes in two flavors-one that takes a single style property and its value and one that takes a map of property-value pairs:

.css(‘property’,’value’)
.css({property1: ‘value1′, ‘property-2′: ‘value2′})

Experienced JavaScript developers will recognize these jQuery maps as JavaScript object literals.

Numeric values do not take quotation marks while string values do. However, when using the map notation, quotation marks are not required for property names if they are written in camel-cased DOM notation.

We use the .css() method the same way as using .addClass() -by chaining it to a selector and binding it to an event. To demonstrate this, we’ll use the style switcher example.

<div id=”switcher”>
<div>Text Size</div>
<button id=”switcher-default”>Default</button>
<button id=”switcher-large”>Bigger</button>
<button id=”switcher-small”>Smaller</button>
</div>
<div>
<p>Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty,
and dedicated to the proposition that all men are created
equal.</p>
</div>

By linking to a stylesheet with a few basic style rules, the page can initially look like the following screenshot:

How  to Add Flair to your Actions with jQuery image 1

In this version of the style switcher, we’re using button elements. Clicking on the Bigger and Smaller buttons will increase or decrease the text size of div class speech, while clicking on the Default button will reset div class speech to its original text size.

If all we wanted were to change the font size a single time to a predetermined value, we could still use the .addClass() method. But let’s suppose that now we want the text to continue increasing or decreasing incrementally each time the respective button is clicked. Although it might be possible to define a separate class for each click and iterate through them, a more straightforward approach would be to compute the new text size each time by getting the current size and increasing it by a set factor (for example, 40%).

Our code will start with the $(document).ready() and $(‘#switcher-large’).click() event handlers:

$(document).ready(function() { $(‘#switcher-large’).click(function() { }); });

Next, the font size can be easily discovered by using the .css() method: $(‘div.speech’).css(‘fontSize’). However, because the returned value will include a trailing ‘px’, we’ll need to strip that part in order to perform calculations with the value. Also, when we plan to use a jQuery object more than once, it’s generally a good idea to cache the selector by storing the resulting jQuery object in a variable as well.

$(document).ready(function() {
var $speech = $(‘div.speech’);
$(‘#switcher-large’).click(function() {
var num = parseFloat($speech.css(‘fontSize’), 10);
});
});

The first line inside $(document).ready() now stores a variable for “div itself. Notice the use of a $ in the variable name, $speech. Since $ is a legal character in JavaScript variables, we can use it as a reminder that the variable is storing a jQuery object.

Inside the .click() handler, we use parseFloat() to get the font size property’s number only. The parseFloat() function looks at a string from left to right until it encounters a non-numeric character. The string of digits is converted into a floating-point (decimal) number. For example, it would convert the string ’12′ to the number 12. In addition, it strips non-numeric trailing characters from the string, so ’12px’ becomes 12 as well. If the string begins with a non-numeric character, parseFloat() returns NaN, which stands for Not a Number. The second argument for parseFloat() allows us to ensure that the number is interpreted as base-10 instead of octal or some other representation.

All that’s left to do, if we are increasing by 40%, is to multiply num by 1.4 and then set the font size by concatenating num and ‘px’:

$(document).ready(function() {
var $speech = $(‘div.speech’);
$(‘#switcher-large’).click(function() {
var num = parseFloat($speech.css(‘fontSize’), 10 );
num *= 1.4;
$speech.css(‘fontSize’, num + ‘px’);
});
});

The equation num *= 1.4 is shorthand for num = num * 1.4. We can use the same type of shorthand for the other basic mathematical operations, as well: addition, num += 1.4; subtraction, num -= 1.4; division, num /= 1.4; and modulus (division remainder), num %= 1.4.

Now when a user clicks on the Bigger button, the text becomes larger. Another click, and the text becomes larger still, as shown in the following screenshot:

How  to Add Flair to your Actions with jQuery image 2

To get the Smaller button to decrease the font size, we will divide rather than multiply -num /= 1.4. Better still, we’ll combine the two into a single .click() handler on all “button” elements within

Then, after finding the numeric value, we can either multiply or divide depending on the ID of the button that was clicked. Here is what that code looks like now:

$(document).ready(function() {
var $speech = $(‘div.speech’);
$(‘#switcher button’).click(function() {
var num = parseFloat( $speech.css(‘fontSize’), 10 );
if (this.id == ‘switcher-large’) {
num *= 1.4;
} else if (this.id == ‘switcher-small’) {
num /= 1.4;
}
$speech.css(‘fontSize’, num + ‘px);
});
});

We can access the id property of the DOM element referred to by this, which appears here inside the if and else if statements. Here, it is more efficient to use this than to create a jQuery object just to test the value of a property.

It’s also nice to have a way to return the font size to its initial value. To allow the user to do so, we can simply store the font size in a variable immediately when the DOM is ready. We can then use this value whenever the Default button is clicked. To handle this click, we could add another else if statement. However, perhaps a switch statement would be more appropriate.

$(document).ready(function() {
var $speech = $(‘div.speech’);
var defaultSize = $speech.css(‘fontSize’);
$(‘#switcher button’).click(function() {
var num = parseFloat( $speech.css(‘fontSize’), 10 );
switch (this.id) {
case ‘switcher-large’:
num *= 1.4;
break;
case ‘switcher-small’:
num /= 1.4;
break;
default:
num = parseFloat(defaultSize, 10);
}
$speech.css(‘fontSize’, num + ‘px’);
});
});

Here we’re still checking the value of this.id and changing the font size based on it, but if its value is neither ‘switcher-large’ nor ‘switcher-small’ it will default to the initial font size.

Basic Hide and Show

The basic .hide() and .show() methods, without any parameters, can be thought of as smart shorthand methods for .css(‘display’,’string’), where ‘string’ is the appropriate display value. The effect, as might be expected, is that the matched set of elements will be immediately hidden or shown, with no animation.

The .hide() method sets the inline style attribute of the matched set of elements to display:none. The smart part here is that it remembers the value of the display property-typically block or inline-before it was changed to none. Conversely, the .show() method restores the matched set of elements to whatever visible display property they had before display:none was applied.

For more information about the display property and how its values are visually represented in a web page, visit the Mozilla Developer Center at https://developer.mozilla.org/en/CSS/display/ and view examples at https://developer.mozilla.org/samples/cssref/display.html.

This feature of .show() and .hide() is especially helpful when hiding elements whose default display property is overridden in a stylesheet. For example, the li element has the property display:block by default, but we might want to change it to display:inline for a horizontal menu. Fortunately, using the .show() method on a hidden element such as one of these li tags would not merely reset it to its default display:block, because that would put the li on its own line. Instead, the element is restored to its previous display:inline state, thus preserving the horizontal design.

A quick demonstration of these two methods can be set up by adding a second paragraph and a “read more” link after the first paragraph in the example HTML:

<div id=”switcher”>
<div>Text Size</div>
<button id=”switcher-default”>Default</button>
<button id=”switcher-large”>Bigger</button>
<button id=”switcher-small”>Smaller</button>
</div>
<div>
<p>Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty,
and dedicated to the proposition that all men are
created equal.
</p>
<p>Now we are engaged in a great civil war, testing whether
that nation, or any nation so conceived and so dedicated,
can long endure. We are met on a great battlefield of
that war. We have come to dedicate a portion of that
field as a final resting-place for those who here gave
their lives that the nation might live. It is altogether
fitting and proper that we should do this. But, in a
larger sense, we cannot dedicate, we cannot consecrate,
we cannot hallow, this ground.
</p>
<a href=”/img_articles/17836/#”>read more</a>
</div>

When the DOM is ready, the second paragraph is hidden:

$(document).ready(function() {
$(‘p:eq(1)’).hide();
});

And the speech looks like the following screenshot:

How  to Add Flair to your Actions with jQuery image 3

Then, when the user clicks on read more at the end of the first paragraph, that link is hidden and the second paragraph is shown:

$(document).ready(function() {
$(‘p:eq(1)’).hide();
$(‘a.more’).click(function() {
$(‘p:eq(1)’).show();
$(this).hide();
return false;
});
});

Note the use of return false to keep the link from activating its default action. Now the speech looks like this:

How  to Add Flair to your Actions with jQuery image 4

The .hide() and .show() methods are quick and useful, but they aren’t very flashy. To add some flair, we can give them a speed.

Effects and Speed

When we include a speed (or, more precisely, a duration) with .show() or .hide(), it becomes animated-occurring over a specified period of time. The .hide(‘speed’) method, for example, decreases an element’s height, width, and opacity simultaneously until all three reach zero, at which point the CSS rule display:none is applied. The .show(‘speed’) method will increase the element’s height from top to bottom, width from left to right, and opacity from 0 to 1 until its contents are completely visible.

Speeding In

With any jQuery effect, we can use one of three preset speeds: ‘slow’, ‘normal’, and ‘fast’. Using .show(‘slow’) makes the show effect complete in .6 seconds, .show(‘normal’) in .4 seconds, and .show(‘fast’) in .2 seconds. For even greater precision we can specify a number of milliseconds, for example .show(850). Unlike the speed names, the numbers are not wrapped in quotation marks.

Let’s include a speed in our example when showing the second paragraph of Lincoln’s Gettysburg Address:

$(document).ready(function() {
$(‘p:eq(1)’).hide();
$(‘a.more’).click(function() {
$(‘p:eq(1)’).show(‘slow’);
$(this).hide();
return false;
});
});

When we capture the paragraph’s appearance at roughly halfway through the effect, we see something like the following:

How  to Add Flair to your Actions with jQuery image 5

Fading In and Fading Out

While the animated .show() and .hide() methods are certainly flashy, they may at times be too much of a good thing. Fortunately, jQuery offers a couple other pre-built animations for a more subtle effect. For example, to have the whole paragraph appear just by gradually increasing the opacity, we can use .fadeIn(‘slow’) instead:

$(document).ready(function() {
$(‘p:eq(1)’).hide();
$(‘a.more’).click(function() {
$(‘p:eq(1)’).fadeIn(‘slow’);
$(this).hide();
return false;
});
});

This time when we capture the paragraph’s appearance halfway, it’s seen as:

How  to Add Flair to your Actions with jQuery image 6

The difference here is that the .fadeIn() effect starts by setting the dimensions of the paragraph so that the contents can simply fade into it. To gradually decrease the opacity we can use .fadeOut().

Compound Effects

Sometimes we have a need to toggle the visibility of elements, rather than displaying them once as we did in the previous example. Toggling can be achieved by first checking the visibility of the matched elements and then attaching the appropriate method. Using the fade effects again, we can modify the example script to look like this:

$(document).ready(function() {
var $firstPara = $(‘p:eq(1)’);
$firstPara.hide();
$(‘a.more’).click(function() {
if ($firstPara.is(‘:hidden’)) {
$firstPara.fadeIn(‘slow’);
$(this).text(‘read less’);
} else {
$firstPara.fadeOut(‘slow’);
$(this).text(‘read more’);
}
return false;
});
});

As we did earlier in the article, we’re caching our selector here to avoid repeated DOM traversal. Notice, too, that we’re no longer hiding the clicked link; instead, we’re changing the its text.

Using an if else statement is a perfectly reasonable way to toggle elements’ visibility. But with jQuery’s compound effects we can leave the conditionals out of it (although, in this example, we still need one for the link text). jQuery provides a .toggle() method, which acts like .show() and .hide(), and like them, can be used with a speed argument or without. The other compound method is .slideToggle(), which shows or hides elements by gradually increasing or decreasing their height. Here is what the script looks like when we use the .slideToggle() method:

$(document).ready(function() {
var $firstPara = $(‘p:eq(1)’);
$firstPara.hide();
$(‘a.more’).click(function() {
$firstPara.slideToggle(‘slow’);
var $link = $(this);
if ( $link.text() == “read more” ) {
$link.text(‘read less’);
} else {
$link.text(‘read more’);
}
return false;
});
});

This time $(this) would have been repeated, so we’re storing it in the $link variable for performance and readability. Also, the conditional statement checks for the text of the link rather than the visibility of the second paragraph, since we’re only using it to change the text.

Creating Custom Animations

In addition to the pre-built effect methods, jQuery provides a powerful .animate() method that allows us to create our own custom animations with fine-grained control. The .animate() method comes in two forms. The first takes up to four arguments:

A map of style properties and values-similar to the .css() map discussed earlier in this article

An optional speed-which can be one of the preset strings or a number of milliseconds

An optional easing type-an advanced option

An optional callback function-which will be discussed later in this article

All together, the four arguments look like this:

.animate({property1: ‘value1′, property2: ‘value2′},
speed, easing, function() {
alert(‘The animation is finished.’);
}
);

The second form takes two arguments, a map of properties and a map of options.

.animate({properties}, {options})

In effect, the second argument wraps up the second through fourth arguments of the first form into another map, and adds two more options to the mix. When we adjust the line breaks for readability, the second form looks like this:

.animate({
property1: ‘value1′,
property2: ‘value2′
}, {
duration: ‘value’,
easing: ‘value’,
complete: function() {
alert(‘The animation is finished.’);
},
queue: boolean,
step: callback
});

For now we’ll use the first form of the .animate() method, but we’ll return to the second form later in the article when we discuss queuing effects.

Toggling The Fade

When we discussed compound effects, did you notice that not all methods have a corresponding method for toggling? That’s right: while the sliding methods include .slideToggle(), there is no corresponding .fadeToggle() to go along with .fadeIn() and .fadeOut()! The good news is that we can use the .animate() method to easily make our own toggling fade animation. Here we’ll replace the .slideToggle() line of the previous example with our custom animation:

$(document).ready(function() {
$(‘p:eq(1)’).hide();
$(‘a.more’).click(function() {
$(‘p:eq(1)’).animate({opacity: ‘toggle’}, ‘slow’);
var $link = $(this);
if ( $link.text() == “read more” ) {
$link.text(‘read less’);
} else {
$link.text(‘read more’);
}
return false;
});
});

As the example illustrates, the .animate() method provides convenient shorthand values for CSS properties – ‘show’, ‘hide’, and ‘toggle’ – to ease the way when the shorthand methods aren’t quite right for the particular task.

animating Multiple Properties

With the .animate() method, we can modify any combination of properties simultaneously. For example, to create a simultaneous sliding and fading effect when toggling the second paragraph, we simply add the height property-value pair to .animate()’s properties map:

$(document).ready(function() {
$(‘p:eq(1)’).hide();
$(‘a.more’).click(function() {
$(‘p:eq(1)’).animate({
opacity: ‘toggle’,
height: ‘toggle’
},
‘slow’);
var $link = $(this);
if ( $link.text() == “read more” ) {
$link.text(‘read less’);
} else {
$link.text(‘read more’);
}
return false;
});
});

Additionally, we have not only the style properties used for the shorthand effect methods at our disposal, but also other properties such as: left, top, fontSize, margin, padding, and borderWidth. Recall the script to change the text size of the speech paragraphs. We can animate the increase or decrease in size by simply substituting the .animate() method for the .css() method:

$(document).ready(function() {
var $speech = $(‘div.speech’);
var defaultSize = $speech.css(‘fontSize’);
$(‘#switcher button’).click(function() {
var num = parseFloat( $speech.css(‘fontSize’), 10 );
switch (this.id) {
case ‘switcher-large’:
num *= 1.4;
break;
case ‘switcher-small’:
num /= 1.4;
break;
default:
num = parseFloat(defaultSize, 10);
}
$speech.animate({fontSize: num + ‘px’},
‘slow’);
});
});

The extra properties allow us to create much more complex effects, too. We can, for example, move an item from the left side of the page to the right while increasing its height by 20 pixels and changing its border width to 5 pixels.

So, let’s do that with the “div id=”switcher” box. Here is what it looks like before we animate it:

How  to Add Flair to your Actions with jQuery image 7

With a flexible-width layout, we need to compute the distance that the box needs to travel before it lines up at the right side of the page. Assuming that the paragraph’s width is 100%, we can subtract the Text Size box’s width from the paragraph’s width. While jQuery’s .width() method would usually come in handy for such calculations, it doesn’t factor in the width of the right and left padding or the right and left border. As of jQuery version 1.2.6, though we also have the .outerWidth() method at our disposal. This is what we’ll use here, to avoid having to add padding and border widths as well. For the sake of this example, we’ll trigger the animation by clicking the Text Size label, just above the buttons. Here is what the code should look like:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher.animate({left: paraWidth – switcherWidth,
height: ‘+=20px’, borderWidth: ’5px’}, ‘slow’);
});
});

Note that the height property has += before the pixel value. This expression, introduced in jQuery 1.2, indicates a relative value. So, instead of animating the height to 20 pixels, the height is animated to 20 pixels greater than the current height.

Although this code successfully increases the height of the “div” and widens its border, at the moment the left position cannot be changed. We still need to enable changing its position in the CSS.

Positioning With CSS

When working with .animate(), it’s important to keep in mind the limitations that CSS imposes on the elements that we wish to change. For example, adjusting the left property will have no effect on the matching elements unless those elements have their CSS position set to relative or absolute. The default CSS position for all block-level elements is static, which accurately describes how those elements will remain if we try to move them without first changing their position value.

For more information on absolute and relative positioning, see Joe Gillespie’s article, Absolutely Relative at: www.wpdfd.com
A peek at our stylesheet shows that we have now set div id switcher to be relatively positioned:

#switcher {
position: relative;
}

With the CSS taken into account, the result of clicking on Text Size, when the animation has completed, will look like this:

How  to Add Flair to your Actions with jQuery image 8

Simultaneous Versus Queued Effects

The .animate() method, as we’ve just discovered, is very useful for creating simultaneous effects in a particular set of elements. There may be times, however, when we want to queue our effects, having them occur one after the other.

Working With A Single Set Of Elements

When applying multiple effects to the same set of elements, queuing is easily achieved by chaining those effects. To demonstrate this queuing, we’ll again move the Text Size box to the right, increase its height and increase its border width. This time, however, we perform the three effects sequentially, simply by placing each in its own .animate() method and chaining the three together:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.animate({left: paraWidth – switcherWidth},
‘slow’)
.animate({height: ‘+=20px’}, ‘slow’)
.animate({borderWidth: ’5px’}, ‘slow’);
});
});

Chaining permits us to keep all three .animate() methods on the same line, but here we have indented them and put each on its own line for greater readability.

We can queue any of the jQuery effect methods, not just .animate(), by chaining them. We can, for example, queue effects on div id switcher in the following order:

Fade its opacity to .5 with .fadeTo().

Move it to the right with .animate().

Fade it back in to full opacity with .fadeTo().

Hide it with .slideUp().

Show it once more with .slideDown().

All we need to do is chain the effects in the same order in our code:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo(‘fast’,0.5)
.animate({
‘left’: paraWidth – switcherWidth
}, ‘slow’)
.fadeTo(‘slow’,1.0)
.slideUp(‘slow’)
.slideDown(‘slow’);
});
});

But what if we want to move the div to the right at the same time as it fades to half opacity? If the two animations were occurring at the same speed, we could simply combine them into a single .animate() method. But in this example, the fade is using the ‘fast’ speed while the move to the right is using the ‘slow’ speed. Here is where the second form of the .animate() method comes in handy:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo(‘fast’,0.5)
.animate({
‘left’: paraWidth – switcherWidth
}, {duration: ‘slow’, queue: false})
.fadeTo(‘slow’,1.0)
.slideUp(‘slow’)
.slideDown(‘slow’);
});
});

The second argument, an options map, provides the queue option, which when set to false makes the animation start simultaneously with the previous one.

One final observation about queuing effects on a single set of elements is that queuing does not automatically apply to other, non-effect methods such as .css(). So let’s suppose we wanted to change the background color of “div id=”switcher” to red after the .slideUp() but before the slideDown(). We could try doing it like this:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo(‘fast’,0.5)
.animate({
‘left’ paraWidth – switcherWidth
}, ‘slow’)
.fadeTo(‘slow’,1.0)
.slideUp(‘slow’)
.css(‘backgroundColor’,’#f00′)
.slideDown(‘slow’);
});
});

However, even though the background-changing code is placed at the correct position in the chain, it occurs immediately upon the click.

One way we can add non-effect methods to the queue is to use the appropriately named .queue() method. Here is what it would look like in our example:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo(‘fast’,0.5)
.animate({
‘left’: paraWidth – switcherWidth
}, ‘slow’)
.fadeTo(‘slow’,1.0)
.slideUp(‘slow’)
.queue(function() {
$switcher
.css(‘backgroundColor’, ‘#f00′)
.dequeue();
})
.slideDown(‘slow’);
});
});

When given a callback function, as it is here, the .queue() method adds the function to the queue of effects for the matched elements. Within the function, we set the background color to red and then add the corollary .dequeue() method. Including this .dequeue() method allows the animation queue to pick up where it left off and complete the chain with the following .slideDown(‘slow’) line. If we hadn’t used .dequeue(), the animation would have stopped.

More information and examples for .queue() and .dequeue() are available at docs.jquery.com.

We’ll discover another way to queue non-effect methods as we examine effects with multiple sets of elements.

Working With Multiple Sets Of Elements

Unlike with a single set of elements, when we apply effects to different sets, they occur at virtually the same time. To see these simultaneous effects in action, we’ll slide one paragraph down while sliding another paragraph up. First, we’ll add the remaining portion of the Gettysburg Address to the HTML, dividing it into two separate paragraphs:

<div id=”switcher”>
<div>Text Size</div>
<button id=”switcher-default”>Default</button>
<button id=”switcher-large”>Bigger</button>
<button id=”switcher-small”>Smaller</button>
</div>
<div>
<p>Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty, and
dedicated to the proposition that all men are created
equal.
</p>
<p>Now we are engaged in a great civil war, testing whether
that nation, or any nation so conceived and so dedicated,
can long endure. We are met on a great battlefield of
that war. We have come to dedicate a portion of that
field as a final resting-place for those who here gave
their lives that the nation might live. It is altogether
fitting and proper that we should do this. But, in a
larger sense, we cannot dedicate, we cannot consecrate,
we cannot hallow, this ground.
</p>
<a href=”/img_articles/17836/#”>read more</a>
<p>The brave men, living and dead, who struggled
here have consecrated it, far above our poor
power to add or detract. The world will little
note, nor long remember, what we say here, but it
can never forget what they did here. It is for us
the living, rather, to be dedicated here to the
unfinished work which they who fought here have
thus far so nobly advanced.
</p>
<p>It is rather for us to be here dedicated to the
great task remaining before us-that from
these honored dead we take increased devotion to
that cause for which they gave the last full
measure of devotion-that we here highly
resolve that these dead shall not have died in
vain-that this nation, under God, shall
have a new birth of freedom and that government
of the people, by the people, for the people,
shall not perish from the earth.
</p>
</div>

Next, to help us see what’s happening during the effect, we’ll give the third paragraph a 1-pixel border and the fourth paragraph a gray background. We’ll also hide the fourth paragraph when the DOM is ready:

$(document).ready(function() {
$(‘p:eq(2)’).css(‘border’, ’1px solid #333′);
$(‘p:eq(3)’).css(‘backgroundColor’, ‘#ccc’).hide();
});

Finally, we’ll add the .click() method to the third paragraph so that when it is clicked, the third paragraph will slide up (and out of view), while the fourth paragraph slides down (and into view):

$(document).ready(function() {
$(‘p:eq(2)’)
.css(‘border’, ’1px solid #333′)
.click(function() {
$(this).slideUp(‘slow’)
.next().slideDown(‘slow’);
});
$(‘p:eq(3)’).css(‘backgroundColor’, ‘#ccc’).hide();
});

A screenshot of these two effects in mid-slide confirms that they do, indeed, occur virtually simultaneously:

How  to Add Flair to your Actions with jQuery image 9

The third paragraph, which started visible, is halfway through sliding up at the same time as the fourth paragraph, which started hidden, is halfway through sliding down.

Callbacks

In order to allow queuing effects on different elements, jQuery provides a callback function for each effect method. As we have seen with event handlers and with the .queue() method, callbacks are simply functions passed as method arguments. In the case of effects, they appear as the last argument of the method.

If we use a callback to queue the two slide effects, we can have the fourth paragraph slide down before the third paragraph slides up. Let’s first look at how to set up the .slideDown() method with the callback:

$(document).ready(function() {
$(‘p:eq(2)’)
.css(‘border’, ’1px solid #333′)
.click(function() {
$(this).next().slideDown(‘slow’,function() {
// code here executes after 3rd paragraph’s
// slide down has ended
});
});
$(‘p:eq(3)’).css(‘backgroundColor’, ‘#ccc’).hide();
});

We do need to be careful here, however, about what is actually going to slide up. The context has changed for $(this) because the callback is inside the .slideDown() method. Here, $(this) is no longer the third paragraph, as it was at the point of the .click() method; rather, since the .slideDown() method is attached to $(this).next(), everything within that method now sees $(this) as the next sibling, or the fourth paragraph. Therefore, if we put $(this).slideUp(‘slow’) inside the callback, we would end up hiding the same paragraph that we had just made visible.

A simple way to keep the reference of $(this) stable is to store it in a variable right away within the .click() method, like var $thirdPara = $(this).

Now $thirdPara will refer to the third paragraph, both outside and inside the callback. Here is what the code looks like using our new variable:

$(document).ready(function() {
var $thirdPara = $(‘p:eq(2)’);
$thirdPara
.css(‘border’, ’1px solid #333′)
.click(function() {
$(this).next().slideDown(‘slow’,function() {
$thirdPara.slideUp(‘slow’);
});
});
$(‘p:eq(3)’).css(‘backgroundColor’, ‘#ccc’).hide();
});

Using $thirdPara inside the .slideDown() callback relies on the properties of closures.

This time a snapshot halfway through the effects will reveal that both the third and the fourth paragraphs are visible; the fourth has finished sliding down and the third is about to begin sliding up:

How  to Add Flair to your Actions with jQuery image 10

Now that we’ve discussed callbacks, we can return to the code from earlier in this article in which we queued a background-color change near the end of a series of effects. Instead of using the .queue() method, as we did earlier, we can simply use a callback function:

$(document).ready(function() {
$(‘div.label’).click(function() {
var paraWidth = $(‘div.speech p’).outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo(‘slow’,0.5)
.animate({
‘left’: paraWidth – switcherWidth
}, ‘slow’)
.fadeTo(‘slow’,1.0)
.slideUp(‘slow’, function() {
$switcher
.css(‘backgroundColor’, ‘#f00′);
})
.slideDown(‘slow’);
});
});

Here again, the background color of div id switcher changes to red after it slides up, and before it slides back down.

In a Nutshell

With all the variations to consider when applying effects, it can become difficult to remember whether the effects will occur simultaneously or sequentially. A brief outline might help:

Effects on a single set of elements are:
- simultaneous when applied as multiple properties in a single .animate() method.
- queued when applied in a chain of methods, unless the queue option is set to false.

Effects on multiple sets of elements are:
- simultaneous by default
- queued when applied within the callback of another effect or within the callback of the .queue() method

Summary

By using effect methods that we have explored in this article, we should now be able to incrementally increase and decrease text size by using either the .css() or the .animate() method. We should also be able to apply various effects to gradually hide and show page elements in different ways and also to animate elements, simultaneously or sequentially, in a number of ways.

Leave a comment »

Horizontal Pop-Up Menu

This tutorial expands on my last CSS pop up menu tutorial.

This second part focuses on changing the menu so that it is horizontal, with the pop ups dropping downwards.

Essentially, the code itself works in the same way and stays pretty similar. The HTML code stays exactly the same as it was and we’ll just edit the CSS to achieve what we’re after.

First up we need to change this part of the CSS:

ul {
list-style: none;
width: 125px;
}

into:

ul {
list-style: none;
}

By removing the “width: 125px” part, the menu is not limited in its width, and so each menu item has room to sit next to each other.

With this one change to our original code the menu already spans horizontally, click here to see an example.

As you can see, a bit of styling is needed to make it look better. So the next step is to change this block of code:

ul li {
border-bottom: 1px solid #FFF;
float: left;
position: relative;
}

into:

ul li {
border-bottom: 1px solid #FFF;
border-right: 1px solid #FFF;
float: left;
position: relative;
}

This will give each menu item a white right hand border – separating each menu item in the style we’re using in the example.

Check here what it looks like now.

Now comes the part that will make the “pop ups” drop downwards. We need to change this part of the code:

ul li ul {
list-style: none;
position: absolute;
left: 140px;
top: 0;
display: none;
width: 125px;
border-left: 1px solid #FFF;
}

into:

ul li ul {
list-style: none;
position: absolute;
left: 0;
top: 100%;
display: none;
width: 125px;
border-top: 1px solid #FFF;
}

All that’s changing now is the “top” and “left” values.

Previously these values told the “pop ups” to appear to this side (by setting “left” to the width of a menu item), now though, we want it below.

So the left value is set to 0 (so its in line with its parent menu item) and set the top to 100% (so it appears after the full height of its parent vertically).

For styling purposes “border-left” has been changed to “border-top” as it is the top of the menu, not the left, that is now adjacent to the main menu.

As you can see here, this places the dropdown below the menu.

Finally, we’ll need to change the secondary pop up menu (products) to behave as it used to (to the side). By replacing this code:

ul li ul li:hover ul { display: block; }

into:

ul li ul li:hover ul {
display: block;
position: absolute;
left: 140px;
top: -1px;
border-left: 1px solid #FFF;
}

It will behave so. The above code is the same as the code from the last tutorial, only this time it is only applied to the secondary navigation.

Now we have a fully functioning horizontal pop up menu! Click here to see it in action!

I hope you enjoyed it, and now will use it in all your wonderful sites!!!

Leave a comment »

Theo dõi

Get every new post delivered to your Inbox.