Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

March 07 2012

10:00

SliderWall Giveaway Winners Announcement!

It has been a week since we started the SliderWall Giveaway and it’s now time to draw the winners! Who could be the lucky five winners of Commercial Licenses of jQuery Image Slider? Read more to find out!

For those who didn’t win, do not worry! SliderWall is not that expensive, it’s well-priced and if you want you can try it for free. Because when it comes to your website you should be thinking about how to make it look cool!

So, who are the winners?

The Winners:

  1. Janet – #16
  2. Juli Weirback – #8
  3. Martin – #5
  4. Hai Nghiem – #13
  5. Von Ferrer – #23

Numbers correspond to the commenter’s number here.

Note to the winners: please check your inbox!

Congratulations!

The Prize:

A commercial license for 1 domain worth $99 with complete features. SliderWall is fully customizable (except the free version). If you are endowed with enough creative senses and has some knowledge of CSS then you can customize SliderWall however you want.

Why Use SliderWall?

  • If you’re tired of old image galeries and would want to find a more interactive way to present your works.
  • If many of your visitors use mobile devices. SliderWall is easily accessible through mobile devices.
  • If you want your website’s search engine rankings to improve.
  • If you want full control of the design.

Use SliderWall for Tours and Presentations

Use SliderWall as an Image Slider

Use SliderWall for Video Clips

Use Sliderwall for just about anything you want to present to the whole world! It’s easy to use, has a lot of cool features, and it makes your website a thousand times cooler!

Didn’t Win?

Don’t worry, you can still use SliderWall for free! Before you decide on buying it, it is prudent that you try it first. But I can assure you that a lot of people are looking forward to having this magnificent image slider!

Other Products:

March 07 2011

23:21

Code Your Own Juicy Tabbed Slider (using the Nivo Slider)


A week ago, on our sister-site, Webdesigntuts+, we showed you how to design a “Juicy Tabbed Slider” in Photoshop. Today we’re going to show you how to actually code it in a few quick steps. No heavy CSS or Javascript knowledge required – promise! We’ll be using the popular Nivo Slider to handle the animation, so let’s dig in!


Let’s Dig In!

Alright, so assuming that you’ve gone through the design phase of this tutorial, now you should have a pretty basic slider element in Photoshop (or Fireworks) format. I’m going to write up this tutorial as a “standalone” slider – meaning it’ll essentially be the only element on the page that we create… but using just a few extra steps after the fact, you should be able to add this to your own designs and position/resize it any way that you want!

What’s better is that this is completely skinnable and resizable – so if you’ve made any heavy customizations in the free PSD that we handed out, you’ll be able to incorporate your franken-modifications here as well!


Step 1: Download the Nivo Slider

Go ahead and download the latest version of the Nivo Slider from their page. The version we’ll be using is Version 2.4, but unless they completely overhaul their entire codebase, chances are very good that the steps in this tutorial will still work in version 2.5, 2.6, and ever onward.

It’s important to note that we’re not re-inventing the wheel here. We’re pretty much just going to be using their “demo.html” file as our own base of operations. We won’t deviate far from the official Usage Documentation either.

As a web designer, I do a lot of work where I’m simply modifying and hijacking other people’s open source code – you probably do the same. It’s an important skill to have unless you’re intent on learning each and every major coding language out there and you’re willing to constantly keep your knowledge up to date. Frankly, I think that’s kind of silly – so figuring out how to use other people’s code is one of the most important skills that you can have.

In most cases (as in this one), all that’s truly required is a rough knowledge of HTML and CSS and the ability to read documentation.

We’ll start out the next step by opening up the “demo” folder – so go ahead and do that before we move on.


Step 2: Understanding the Basic Setup

In this step, we’re simply going to attempt to get an idea for how the Nivo Slider works. Every slider out there is going to work a little bit different, so it’s worth taking a few minutes to familiarize yourself with the particular script that you intend to use on a project.

If you take a quick look at the code for the Nivo Slider (inside the demo.html file), you’ll notice that all of the major styling and structure is being handled from the “style.css” file. In fact, the actual HTML code is pretty simple once you’ve referenced the appropriate scripts in the HEAD section of demo.html.

Let’s start our walkthrough by looking at the lines of code from the header. We won’t need to change these, but they need to be present in any file that we want to use the slider on:

<!-- Usually in the <head> section -->
<link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.nivo.slider.pack.js"></script>

Next, let’s peek at the raw HTML that generates the slider:

<!-- Then somewhere in the <body> section -->
<div id="slider">
    <img src="images/slide1.jpg" alt="" />
    <a href="http://dev7studios.com">
    	<img src="images/slide2.jpg" alt="" title="#htmlcaption" />
    </a>
    <img src="images/slide3.jpg" alt="" title="This is an example of a caption" />
    <img src="images/slide4.jpg" alt="" />
</div>

Finally, we won’t be dealing with captions in this particular slider, so you can pretty much disregard the next lines (unless you want to do your own customization of the slider later on):

<div id="htmlcaption" class="nivo-html-caption">
    <strong>This</strong> is an example of a <em>HTML</em> caption with <a href="#">a link</a>.
</div>

So, really, all that’s required for you to understand is the basic HTML that generates the slider (shown above in the second block of code). Since we won’t be dealing with captions in our slider, you can further simplify the code to something like this:

<div id="slider-wrapper">
    <div id="slider">
        <img src="images/slide1.jpg" alt="" />
        <img src="images/slide2.jpg" alt="" />
        <img src="images/slide3.jpg" alt="" />
        <img src="images/slide4.jpg" alt="" />
    </div>
</div>

That’s not so bad right? It’s essentially just a couple wrapped DIV elements with images inside.


The CSS for the Nivo Slider

The CSS is what’s going to be doing the heavy lifting, so let’s take a peek at that:

/*============================*/
/*=== Custom Slider Styles ===*/
/*============================*/
#slider-wrapper {
    background:url(images/slider.png) no-repeat;
    width:998px;
    height:392px;
    margin:0 auto;
    padding-top:74px;
    margin-top:50px;
}

#slider {
	position:relative;
    width:618px;
    height:246px;
    margin-left:190px;
	background:url(images/loading.gif) no-repeat 50% 50%;
}
#slider img {
	position:absolute;
	top:0px;
	left:0px;
	display:none;
}
#slider a {
	border:0;
	display:block;
}

.nivo-controlNav {
	position:absolute;
	left:260px;
	bottom:-42px;
}
.nivo-controlNav a {
	display:block;
	width:22px;
	height:22px;
	background:url(images/bullets.png) no-repeat;
	text-indent:-9999px;
	border:0;
	margin-right:3px;
	float:left;
}
.nivo-controlNav a.active {
	background-position:0 -22px;
}

.nivo-directionNav a {
	display:block;
	width:30px;
	height:30px;
	background:url(images/arrows.png) no-repeat;
	text-indent:-9999px;
	border:0;
}
a.nivo-nextNav {
	background-position:-30px 0;
	right:15px;
}
a.nivo-prevNav {
	left:15px;
}

.nivo-caption {
    text-shadow:none;
    font-family: Helvetica, Arial, sans-serif;
}
.nivo-caption a {
    color:#efe9d1;
    text-decoration:underline;
}

If you’re new to CSS, this might look intimidating at first… but most of you will see this for a fairly simple bit of styling code. Everything you need to resize and reskin the slider is here… and we only need to change a handful of lines of script to get this thing looking exactly like our version.

First though, we need to locate and re-skin the images that are currently being used for the slider with our own. If you open up the “/demo/images/” folder, you’ll see there’s just a couple main images that we want to reskin:

  • arrows.png (the Left / Right arrows)
  • bullets.png (the Dot indicators)
  • slider.png (the background frame)
  • background.png (optional)
  • loading.png (optional)

Re-skinning the Assets

If we were coding this slider from scratch, we’d probably start by carefully chopping it in Photoshop, piece by piece. However, since we’re working with a pre-existing set of “assets” (aka, the images used to create the background, bullets and arrows), it’s going to make a little bit more sense to skin the pre-existing assets rather than start from scratch.

Reskin the Bullets

Let’s start with the “bullets.png” file since it happens to be the most straight forward file. Go ahead and open it up in Photoshop:

Notice the basic structure of the file here. There are two graphics that will be positioned using CSS so that one appears at a time.

We already have our own bullet graphics from our own PSD, so we simply want to position them over the original elements and re-save the file:

In this case, we don’t even need to re-size the file at all… so we’re actually done reskinning the bullets! Save this new file over the original “bullets.png”.

Reskin the Arrows

The arrows are going to be one level more difficult, simply because our arrow graphics are larger than the original graphics. That’s fine though – we’ll still start by opening up the “arrows.png” file inside Photoshop.


It’s hard to see the arrows because they are transparent.

Once again, notice the structure of the file – two arrows, side by side this time – that will be positioned using CSS so that only one appears at a time.

The size of the graphic is 60x30px… but ours will have to be large enough to hold both of our bigger arrows. Having measured our own arrows (you can do this using the Rectangular Marquee tool and the Info panel), I’ve decided that the new dimensions should be 70x65px. This will be large enough to hold both arrows, as well as the light shadow that we want to appear next to each one.

We’re going to have to make a few changes to the size and positioning in the CSS, but this completes the initial reskin for the arrows. Save this new file over the original “arrows.png”.

Reskin the Background

Lastly, let’s re-skin the background graphic. The Nivo Slider demo uses an abstract sort of circle background – but we want to use our “frame and shadow” graphic for the background.

This swap is going to be similar to what we did with the arrows, but instead of needing to make our image larger, this time we actually need to save a smaller document. Notice how large the original image is:


998x392px – Scaled Down for the Site.

998x392px is the original background’s dimensions – We want it to be closer to 494x310px to match our own frame. This isn’t tough, but it’s a case where it’s going to make more sense just to grab a direct slice from our original PSD file.

Go ahead and turn off ALL layers (including the background) other than the frame and the shadow, then Crop the image down to about 20-25px of spacing around the frame just to be safe (we won’t want to accidentally crop our shadow):

As with the last two graphics, go ahead and save directly over the original image “slider.png”.


Save Our Image Slides

The original slider uses images that are 618×246 in size. Our slider uses images that are 430x250px though, so we need to save over the original slide images using our own cropped in versions. You can obviously use your own images here… but for the sake of simplicity, I’ve just cropped in the Pixar images that the demo used.

If you did want to use your own images, obviously you’ll want to name them uniquely (my_image1.jpg, my_image2.jpg, etc.), and then amend the image paths inside the demo.html document.


Tweaking the CSS to Fit Our New Skinned Images

The last step here is probably the trickiest as it requires a lot of trial and error. Our objective is going to be to tweak the original style.css file so that our slider matches our own design. The primary problem is that the original slider uses completely different dimensions for most of the major elements, so we need to carefully, through trial and error, sort out what our own dimensions should be.

Trial and Error in CSS can be done a few different ways – The “hard” way is to simply keep on tweaking the CSS file, saving it, and then previewing it in the browser. The easy way is to use a browser plugin like Firebug to actually test out your adjustments in the browser itself. If you haven’t picked up Firebug yet, I highly recommend doing so now. It’s a simple plugin that attaches to your browser.

I’m going to simply dish out the completed CSS file right now, then we’ll break it down step by step. I’ll mark every major line that was edited with a “/*= NEW =*/” note:

/*============================*/
/*=== Custom Slider Styles ===*/
/*============================*/
#slider-wrapper {
    background:url(images/slider.png) no-repeat;
    width:494px; /*= NEW =*/
    height:310px;  /*= NEW =*/
    margin:0 auto;
    padding-top:23px; /*= NEW =*/
    margin-top:50px;
}

#slider {
	position:relative;
    width:430px;  /*= NEW =*/
    height:250px;  /*= NEW =*/
    margin-left:32px;  /*= NEW =*/
	background:url(images/loading.gif) no-repeat 50% 50%;
}
#slider img {
	position:absolute;
	top:0px;
	left:0px;
	display:none;
}
#slider a {
	border:0;
	display:block;
}

.nivo-controlNav {
	position:absolute;
	left:163px;  /*= NEW =*/
	bottom:12px;  /*= NEW =*/
	background: #000000;  /*= NEW =*/
	-moz-border-radius: 10px;  /*= NEW =*/
    -webkit-border-radius: 10px;  /*= NEW =*/
    padding: 3px;  /*= NEW =*/
    border: 2px solid #CCC;  /*= NEW =*/
    opacity: 0.7;  /*= NEW =*/
    z-index: 99;  /*= NEW =*/
	}

	.nivo-controlNav:hover{opacity: 1;}  /*= NEW =*/

.nivo-controlNav a {
	display:block;
	width:22px;
	height:22px;
	background:url(images/bullets.png) no-repeat;
	text-indent:-9999px;
	border:0;
	margin-right:0px;  /*= NEW =*/
	float:left;
}
.nivo-controlNav a.active {
	background-position:0 -22px;
}

.nivo-directionNav a {
	display:block;
	width:35px;  /*= NEW =*/
	height:65px;  /*= NEW =*/
	background:url(images/arrows.png) no-repeat;
	text-indent:-9999px;
	border:0;
}
a.nivo-nextNav {
	background-position:-35px 0;  /*= NEW =*/
	right: -40px;  /*= NEW =*/
}

a.nivo-nextNav:hover{right: -41px;}  /*= NEW =*/

a.nivo-prevNav {
	left:-40px;  /*= NEW =*/
}
a.nivo-prevNav:hover{left: -41px;}  /*= NEW =*/

.nivo-caption {
    text-shadow:none;
    font-family: Helvetica, Arial, sans-serif;
}
.nivo-caption a {
    color:#efe9d1;
    text-decoration:underline;
}

.nivo-directionNav a{top: 40%;}  /*= NEW =*/

Looking closely, you’ll notice that all of the changes (with the “/*= NEW =*/” note) fall into the same basic categories:

  • Width
  • Height
  • Positioning (left, right, top, bottom)

The only two exceptions are where we’ve added the background color and rounded corners to the “.nivo-controlNav” element and where we’ve adjusted the default positioning of the “.nivo-directionNav a” element (this second one was previously set by another stylesheet, so we’re overriding the default setting of 45% so our arrows are higher up on the slider).

The other new rule that we’ve added is the “a.nivo-prevNav:hover{left: -41px;}” rules for the left and right buttons. The purpose here is to add a subtle nudge to each button when you mouse over them.

If you’re planning on creating your own resized version of the slider, you’ll want to pay attention to the two spots where the overall height and width of the slider are set. In short, the “#slider-wrapper” and “#slider” elements are what control this – simply adjust the height and width parameters to match your own slider’s dimensions and you should be good to go.


Last Step – UnHiding the Left/Right Arrows

The final modification that I’ve decided to make from the original demo.html file is to unhide the arrow buttons. By default, the Nivo Slide hides these “directional” navigation controls – only showing them when your mouse is hovering over the slider. For us though, these elements are a key aesthetic that we wouldn’t want to hide.

To correct this, the Nivo Slider gives us a simple method of unhiding by adding a single option to the activation script. At the bottom of the demo.html file, find the following:

	<script>
	    $(window).load(function() {
        $('#slider').nivoSlider();
    });
    

Now simply add the following option:

directionNavHide:false

So that the revised code looks like this:

<script>
    $(window).load(function() {
        $('#slider').nivoSlider({directionNavHide:false});
    });
    

There is a full list of customizations that you can make through this method - check out the Usage Page on Nivo Slider's website for more notes.

Conclusion

That’s it for this tutorial! While we haven’t coded a single thing from scratch, we have effective created a custom slider and then realized it in code using one of the best pre-built slider scripts out there on the net right now. I hope you’ve picked up a few new skills in this walkthrough – have fun customizing this and using it in your own design!

Sponsored post
soup-sponsored
20:53
Reposted byLegendaryy Legendaryy

August 19 2010

05:47

April 30 2010

11:00

April 21 2010

15:07

Integrating the Piecemaker 3D Gallery into your WordPress Theme

This tutorial will show you how to successfully integrate the Piecemaker 3D Flash image rotator into your WordPress theme. We’ll also discuss setting up a custom admin panel which will make it super easy for your users to make customizations to the rotator.

Piecemaker is a gorgeous, open-source, 3D Flash image rotator created by Björn Crüger from Modularweb. You can preview the piecemaker in action on Sansation, the first premium WordPress theme on ThemeForest to incorporate Piecemaker.

Piecemaker

Preview


Brief Overview

All of the files included in the ZIP file are already modified for you. We’ve also included a folder which has all of the default unmodified Piecemaker files. I recommend that you go check out the Piecemaker site and familiarize yourself with it before proceeding with the tutorial.


Step 1. Modify the ActionScript

The first step is to modify the ActionScript so that it’ll play nicely with WordPress. The ActionScript that comes with Piecemaker defines three values that the Piecemaker needs in order to function properly:

  • the XML Source
  • the CSS Source
  • the path to the images folder.

The XML Source defines the Picemaker’s various settings and allows you to define images and their descriptions. The CSS file styles the Piecemaker’s description panels, and the images directory tells the Piecemaker where to pull the images from.

Open up the FLA file named “piecemakerNoShadow.fla” and open the Actions window. In frame 1 you will see the actions below. Please note that you need Flash CS4 to open the source file.

In order for the Piecemaker to work properly within our WordPress theme, we need to dynamically set these variables. To achieve this, we will be using FlashVars. FlashVars are variables the we’ll set within our WordPress page template that will get passed to the flash movie when the page loads. Go ahead and delete the default actions in frame 1 of the flash file, and replace them with the following code:

stage.scaleMode = StageScaleMode.NO_SCALE;

// Pull in the Flashvars
var allFlashVars:Object = LoaderInfo(this.root.loaderInfo).parameters;

// Set the required variables for piecemaker
piecemaker.xmlSource = String(allFlashVars.xmlSource);
piecemaker.cssSource = String(allFlashVars.cssSource);
piecemaker.imageSource = String(allFlashVars.imageSource);
piecemaker.dispatchEvent(new Event("properties"));

The above ActionScript first loads in the FlashVars, and then replaces the default Piecemaker values with these new variables. Our Flash file is now all set to go. Publish the SWF and load your FTP client of choice.


Step 2. Upload Files and Folders

The next step is to upload the required files and folders into your WordPress theme’s directory. This tutorial assumes that you will be uploading everything directly into your theme’s main directory. Here is a list of the required items:

  • piecemakerCSS.css
  • piecemakerNoShadow.swf
  • piecemakerXML.xml
  • ‘images’ folder (with your images in it)
  • ’swfobject’ folder (plus contents)
  • piecemakerXML.php (needde for use with the custom admin panel)

Step 3. Embed the SWF and set the FlashVars

The next step is to embed the SWF movie into your WordPress page template. We’ll be using SWFObject 2 to embed the movie, and we’ll also define the three FlashVars that we referenced in step one.

You first need to reference swfobject within the head of your page. To do so, open up your theme’s “header.php” file in your code editor of choice (mine’s BBEdit), and add the following code in the head of your page:

<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/swfobject/swfobject.js"></script>

Next, open up the WordPress page template where you’d like the Piecemaker 3D Rotator to display, and paste the following code:

<div id="flashcontent">
<p>You need to <a href="http://www.adobe.com/products/flashplayer/" target="_blank">upgrade your Flash Player</a> to version 10 or newer.</p>
</div><!-- end flashcontent -->

<script type="text/javascript">
		var flashvars = {};
		flashvars.xmlSource = "<?php bloginfo('template_url'); ?>/piecemakerXML.xml";
		flashvars.cssSource = "<?php bloginfo('template_url'); ?>/piecemakerCSS.css";
		flashvars.imageSource = "<?php bloginfo('template_url'); ?>/images";
		var attributes = {};
		attributes.wmode = "transparent";
		swfobject.embedSWF("<?php bloginfo('template_url'); ?>/piecemakerNoShadow.swf", "flashcontent", "960", "610", "10", "<?php bloginfo('template_url'); ?>/swfobject/expressInstall.swf", flashvars, attributes);
</script>

Code Explaination

The bulk of the code is just your standard swfobject code used to embed a flash movie onto any webpage. The important stuff we need to be concerned with are the FlashVars:

flashvars.xmlSource = "<?php bloginfo('template_url'); ?>/piecemakerXML.xml";
flashvars.cssSource = "<?php bloginfo('template_url'); ?>/piecemakerCSS.css";
flashvars.imageSource = "<?php bloginfo('template_url'); ?>/images";

Notice that we have named our FlashVars just as we defined them in the ActionScript in step on4. We are also using WordPress’ built-in bloginfo() function to reference the exact locations of the three required files.

That’s it! Well, Sort of…

The above steps will enable you to successfully deploy the Piecemaker 3D Image Rotator into your WordPress theme, but we’re going to take it a step further. In the following steps, we will discuss how to create a custom admin panel that will allow you to customize Piecemaker’s settings right from the WordPress back-end.

If you’re not interested in setting up the admin panel, you can go over to the Piecemaker website to read the documentation and start making some really kick-awesome animations.


Step 4. Create The Admin Panel

We will not be covering how to create the entire admin panel from scratch. Instead, we’ll expand upon an already in-depth tutorial here on Nettuts: How to Create a Better WordPress Panel.

Once you have followed that tutorial and you have your admin panel setup, please proceed to the next step.


Step 5. Define Our New Options Panel

We now need to add additional options to the admin panel you just created in the tutorial. Open your theme’s “functions.php” file, and replace the first chunk of code with the following:

<?php
$themename = "Nettuts";
$shortname = "nt";

$categories = get_categories('hide_empty=0&orderby=name');
$wp_cats = array();
foreach ($categories as $category_list ) {
       $wp_cats[$category_list->cat_ID] = $category_list->cat_name;
}
array_unshift($wp_cats, "Choose a category");
$tween_types = array("linear","easeInSine","easeOutSine", "easeInOutSine", "easeInCubic", "easeOutCubic", "easeInOutCubic", "easeOutInCubic", "easeInQuint", "easeOutQuint", "easeInOutQuint", "easeOutInQuint", "easeInCirc", "easeOutCirc", "easeInOutCirc", "easeOutInCirc", "easeInBack", "easeOutBack", "easeInOutBack", "easeOutInBack", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeOutInQuad", "easeInQuart", "easeOutQuart", "easeInOutQuart", "easeOutInQuart", "easeInExpo", "easeOutExpo", "easeInOutExpo", "easeOutInExpo", "easeInElastic", "easeOutElastic", "easeInOutElastic", "easeOutInElastic", "easeInBounce", "easeOutBounce", "easeInOutBounce", "easeOutInBounce");

The bulk of the above code is identical to the tutorial, but we’ve added a new array named $tween_types. This array holds all of the various animation effects that are available with PieceMaker. We will use this array to generate a dropdown list of the various animation effects in our custom options panel. You can check out the Tweener Documentation to review a visual representation of the various Piecemaker animation effects.

Still within the functions.php file, add the following array below the ones you’ve already created in the tutorial.

This will create a new sliding options panel similar to the ones you created in the tutorial. It’s a long bit of code, but it follows the same exact logic as the tutorial. We are simply creating variables for all of the different settings that we’ll need to define in the Piecemaker’s XML file. An important thing to note is that we made sure to define default values for each option (the values in ’std’ are the default values). There are a decent amount of settings for the Piecemaker and we don’t want to force our users to set up all those options if they don’t want to.

array( "name" => "3D Rotator Options",
"type" => "section"),
array( "type" => "open"),

array( "name" => "Segments",
"desc" => "Number of segments in which the image will be sliced.",
"id" => $shortname."_segments",
"type" => "text",
"std" => "9"),

array( "name" => "Tween Time",
"desc" => "Number of seconds for each element to be turned.",
"id" => $shortname."_tween_time",
"type" => "text",
"std" => "3"),

array( "name" => "Tween Delay",
"desc" => "Number of seconds from one element starting to turn to the next element starting.",
"id" => $shortname."_tween_delay",
"type" => "text",
"std" => "0.1"),

array( "name" => "Tween Type",
"desc" => "Type of animation transition.",
"id" => $shortname."_tween_type",
"type" => "select",
"options" => $tween_types,
"std" => "Choose a category"),

array( "name" => "Z Distance",
"desc" => "to which extend are the cubes moved on z axis when being tweened. Negative values bring the cube closer to the camera, positive values take it further away. A good range is roughly between -200 and 700.",
"id" => $shortname."_z_distance",
"type" => "text",
"std" => "25"),

array( "name" => "Expand",
"desc" => "To which etxend are the cubes moved away from each other when tweening.",
"id" => $shortname."_expand",
"type" => "text",
"std" => "9"),

array( "name" => "Inner Color",
"desc" => "Color of the sides of the elements in hex values (e.g. 0x000000 for black)",
"id" => $shortname."_inner_color",
"type" => "text",
"std" => "0x000000"),

array( "name" => "Text Background Color",
"desc" => "Color of the description text background in hex values (e.g. 0xFF0000 for red)",
"id" => $shortname."_text_background",
"type" => "text",
"std" => "0x666666"),

array( "name" => "Text Distance",
"desc" => "Distance of the info text to the borders of its background.",
"id" => $shortname."_text_distance",
"type" => "text",
"std" => "25"),

array( "name" => "Shadow Darkness",
"desc" => "To which extend are the sides shadowed, when the elements are tweening and the sided move towards the background. 100 is black, 0 is no darkening.",
"id" => $shortname."_shadow_darkness",
"type" => "text",
"std" => "25"),

array( "name" => "Auto Play",
"desc" => "Number of seconds to the next image when autoplay is on. Set 0, if you don't want autoplay.",
"id" => $shortname."_autoplay",
"type" => "text",
"std" => "2"),

array( "type" => "close"),

Step 6. Update Our Page Template

In this step, we need to slightly modify our WordPress page template from Step three. Instead of pointing our xmlSource to an XML file, we need to point it to a PHP file. By using a PHP file instead of an XML file, we can pull in all of the values that were set by the user in our custom options panel. It’s just the one line of code that needs to be replaced:

flashvars.xmlSource = "<?php bloginfo('template_url'); ?>/piecemakerXML.php";

Step 7. Generate our XML File with PHP

We’re almost there! In this step, we’ll create the PHP file that we just referenced in the code above. This PHP file will be used to pull in all of the values from our custom options panel and generate the XML file that the Piecemaker needs in order to function properly. The code is somewhat lengthy, so I’ll try to break it up into more digestable chunks.

Create a blank PHP file, name it “piecemakerXML.php”, and paste the following code at the start of the file:

<?php require_once( '../../../wp-load.php' );
$segments = get_option('nt_segments');
$tweentime = get_option('nt_tween_time');
$tweendelay = get_option('nt_tween_delay');
$tweentype = get_option('nt_tween_type');
$zdistance = get_option('nt_z_distance');
$expand = get_option('nt_expand');
$innercolor = get_option('nt_inner_color');
$textbackground = get_option('nt_text_background');
$textdistance = get_option('nt_text_distance');
$shadow = get_option('nt_shadow_darknent');
$autoplay = get_option('nt_autoplay');
?>
  • The first line loads WordPress into our PHP file. This allows us to have access to all of the default WordPress functions, as well as any values stored within our database.
  • The rest of the code pulls in the data from our custom options panel and stores those values into variables. We will use these variables to generate the rest of the Piecemaker’s settings.
  • Next, we need to set the content-type header so that the browser knows we are going to output XML content rather than the default text/html. We will also include some initial Piecemaker settings tags.

    <?php
    header("Content-type: text/xml");
    echo '<?xml version="1.0" encoding="utf-8" ?>
    <Piecemaker>
      <Settings>
    	<imageWidth>830</imageWidth>
    	<imageHeight>360</imageHeight>';
    

    We are now going to output the variables we stored into their correct XML tags, and close out the Piecemaker settings tag.

    echo '<segments>'. $segments . '</segments>';
    echo '<tweenTime>'. $tweentime . '</tweenTime>';
    echo '<tweenDelay>'. $tweendelay . '</tweenDelay>';
    echo '<tweenType>'. $tweentype . '</tweenType>';
    echo '<zDistance>'. $zdistance . '</zDistance>';
    echo '<expand>'. $expand . '</expand>';
    echo '<innerColor>'. $innercolor . '</innerColor>';
    echo '<textBackground>'. $textbackground . '</textBackground>';
    echo '<textDistance>'. $textdistance . '</textDistance>';
    echo '<shadowDarknent>' . $shadow . '</shadowDarknent>';
    echo '<autoplay>' . $autoplay .  '</autoplay>';
    echo '
    </Settings>
    

    The final step is to output the images that we want to include in the rotator along with their descriptions, and we’ll also close out the Piecemaker XML tag.

    <Image Filename="image1.jpg">
        <Text>
          <headline>Description Text</headline>
          <break>Ӂ</break>
          <paragraph>Here you can add a description text for every single slide.</paragraph>
          <break>Ӂ</break>
          <inline>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eu quam dolor, a venenatis nisl. Praesent scelerisque iaculis fringilla. Sed congue placerat eleifend.</inline>
          Ӂ<a href="http://themes.5-squared.com/sansation/?style=cool_blue" target="_blank">hyperlinks</a>
        </Text>
      </Image>
    
      <Image Filename="image2.jpg">
        <Text>
          <headline>Description Text</headline>
          <break>Ӂ</break>
          <paragraph>Here you can add a description text for every single slide.</paragraph>
          <break>Ӂ</break>
          <inline>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eu quam dolor, a venenatis nisl. Praesent scelerisque iaculis fringilla. Sed congue placerat eleifend.</inline>
          Ӂ<a href="http://themes.5-squared.com/sansation/?style=cool_blue" target="_blank">hyperlinks</a>
        </Text>
      </Image>
    
      <Image Filename="image3.jpg">
        <Text>
          <headline>Description Text</headline>
          <break>Ӂ</break>
          <paragraph>Here you can add a description text for every single slide.</paragraph>
          <break>Ӂ</break>
          <inline>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eu quam dolor, a venenatis nisl. Praesent scelerisque iaculis fringilla. Sed congue placerat eleifend.</inline>
          Ӂ<a href="http://themes.5-squared.com/sansation/?style=cool_blue" target="_blank">hyperlinks</a>
        </Text>
      </Image>
    
      <Image Filename="image4.jpg">
        <Text>
          <headline>Description Text</headline>
          <break>Ӂ</break>
          <paragraph>Here you can add a description text for every single slide.</paragraph>
          <break>Ӂ</break>
          <inline>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eu quam dolor, a venenatis nisl. Praesent scelerisque iaculis fringilla. Sed congue placerat eleifend.</inline>
          Ӂ<a href="http://themes.5-squared.com/sansation/?style=cool_blue" target="_blank">hyperlinks</a>
        </Text>
      </Image>
    </Piecemaker>';
    ?>
    

    Conclusion

    I hope you learned something useful in this tutorial. By combining various different technologies, we’re able to add powerful functionality to our WordPress themes. More importantly, we made it easy for the average user to make customizations to our theme.


March 05 2010

17:40

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!


January 05 2010

16:33

A Bullet-Proof Content Viewer

In this tutorial, we’re going to look at how we can easily create an attractive and space-saving content viewer which even works with JavaScript disabled. We’ll build a solid core of semantic HTML, styled with some basic CSS and we’ll then use jQuery to add further enhancements in the form of transition animations.

The following screenshot shows what we’ll end up with by the end of the tutorial:


Getting Started

First, let’s create the underlying HTML page for our content viewer; in a new file in your text editor create the following page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Bullet-proof Content Viewer</title>
        <link rel="stylesheet" type="text/css" href="contentviewer.css">
	</head>
	<body>
    	<div id="viewer">
        	<ul id="nav">
            	<li class="thumb1"><a href="#panel1" title="Panel 1">Panel 1</a></li>
				<li class="thumb2"><a href="#panel2" title="Panel 2">Panel 2</a></li>
				<li class="thumb3"><a href="#panel3" title="Panel 3">Panel 3</a></li>
				<li class="thumb4"><a href="#panel4" title="Panel 4">Panel 4</a></li>
				<li class="thumb5"><a href="#panel5" title="Panel 5">Panel 5</a></li>
			</ul>
			<div id="panels">
				<div id="slider">
               		<div id="panel1">
                    	<img src="img/image1.jpg" alt="Image 1">
						<p>Supernova 1994D, visible as the bright spot at the lower left, occurred in the outskirts of the disk galaxy NGC 4526.</p>
	               	</div>
 					<div id="panel2">
                    	<img src="img/image2.jpg" alt="Image 2">
						<p>Radiation from hot stars off the top of the picture illuminates and erodes this giant, gaseous pillar.</p>
					</div>
					<div id="panel3">
	               		<img src="img/image3.jpg" alt="Image 3">
	 					<p>V838 Mon is located about 20,000 light-years away from Earth at the outer edge of the Milky Way.</p>
					</div>
					<div id="panel4">
	               		<img src="img/image4.jpg" alt="Image 4">
						<p>The Sombrero Galaxy is an unbarred spiral galaxy in the constellation Virgo approximately 30 million lights years away.</p>
					</div>
               			<div id="panel5">
	               		<img src="img/image5.jpg" alt="Image 5">
						<p>This region of active current star formation is part of a diffuse emission nebula about 6,500 light-years away.</p>
					</div>
				</div>
			 </div>
		</div>
		<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
		<script type="text/javascript">
		</script>
	</body>
</html>

Save this as contentviewer.html. We’ll start off with some clean and semantic HTML, using no more elements than is strictly necessary. We have an outer container for the viewer in its entirety, which contains a navigation structure for selecting which content panel to view and a second container for the content panels themselves.

Within the content panel container, we have another container used to enclose all of the content panels (this is needed to display the content panels correctly) and the content panels themselves. Each panel contains an image and a span describing the image.

The main images are added to the document as proper HTML images using the <img> element – this is because they are content and should be visible to assistive technologies or users with both scripting and CSS disabled or otherwise not available. The navigation structure will also contain images, but as these are not classed as content they do not need to be visible in all situations and can therefore be added using CSS, hence the additional class names on the <li> elements.

Right now the page should appear like this:

It doesn’t look great, but the document flows correctly and the elements are all clearly visible and usable.

Making it work with CSS

We can now use CSS to transform the content viewer into a functioning interface that doesn’t look terrible. W already linked to the style sheet in the head of our page so let’s create it now; in a new file in your text editor add the following selectors and rules:

#viewer { width:700px; margin:auto; }
#nav { width:200px; float:left; margin:0; padding:0; list-style-type:none; }
#nav li { width:200px; height:100px; padding:0; }
#nav li a { display:block; width:100%; height:100%; text-indent:-9999px; overflow:hidden; background:url(img/thumbs.png) no-repeat 0 0; }
#nav li a:hover, #nav li a.on { background-position:-200px 0; }
#nav li.thumb2 a { background-position:0 -100px; }
#nav li.thumb2 a:hover, #nav li.thumb2 a.on { background-position:-200px -100px; }
#nav li.thumb3 a { background-position:0 -200px; }
#nav li.thumb3 a:hover, #nav li.thumb3 a.on { background-position:-200px -200px; }
#nav li.thumb4 a { background-position:0 -300px; }
#nav li.thumb4 a:hover, #nav li.thumb4 a.on { background-position:-200px -300px; }
#nav li.thumb5 a { background-position:0 -400px; }
#nav li.thumb5 a:hover, #nav li.thumb5 a.on { background-position:-200px -400px; }
#panels { width:500px; height:500px; overflow:hidden; position:relative; float:left; }

Save this as contentviewer.css in the same directory as the HTML page. I’ve kept the design minimal so that we can focus on what makes it work; the navigation and viewing panel are floated next to each other and the individual list items are given their background images and hover states. We’ve also added on states as well. This part of the CSS is purely for layout/presentation and does not affect functionality.

What’s important is how the containers and content images are arranged. The outer container (#panels) is given a fixed size that matches the height and width of a single content image and has its overflow property set to hidden to ensure that only a single image is displayed at any one time. This is the only really required CSS for the content viewer to work to a basic degree. If you look at the page now, you’ll see that you can click any of the thumbnails and the corresponding full-sized image will be displayed in the viewing panel:

This is great because it remains functional and accessible without relying on JavaScript. We’ll move on to use jQuery to add some smooth transitional effects in just a moment, but first we should add a few more styles that are required for the animations, and to display the paragraphs correctly. Add the following code to the bottom of contentviewer.css:

#slider { width:2500px; height:500px; }
#slider div { float:left; position:relative; }
#slider p { position:absolute; bottom:0; left:0; color:#fff; font:16px "Trebuchet MS"; margin:0; width:90%; height:45px; padding:5px 5% 10px; background-color:#000; }

The inner container (#slider) is given a fixed height equal to a single content image, but a width equal to all of the images. Then the individual containers holding the images and paragraphs are floated to the left to make them stack up horizontally. Finally, the paragraphs are styled and positioned as well so that they overlay each image:

Floating the individual content panels to the left and setting the size of the slider is not strictly necessary, without these the images will just stack up vertically. This would mean that any animations we added would have to move the content panels vertically as well, but we’ll be animating them horizontally.

One point I should make here is that the code so far does not work in Opera; for some reason, Opera cannot use the anchors on the page to show the different content panels when one of the navigation items is clicked. This is a big fail and seems to be a problem in more than one version of Opera. There is a fix apparently and anyone that uses Opera as their main browser will have hopefully implemented this fix already. It isn’t a problem when the JavaScript has been added though.

Adding the jQuery Effects

As the page now works on its own, we can add the JavaScript that will turn this from a functional page into an attractive interface. We left an empty <script> element at the bottom of our page, let’s fill it up now; start with the following code:

(function($){
	//code here...
	})(jQuery);

What we’re doing here with this first bit of code is ensuring that the $ character will always refer to the jQuery object; if this code is to be used on a page with another JS library which also uses the $ character we can be sure that within our code $ will always refer to jQuery. We’re creating an alias for jQuery that matches the $ character by passing the jQuery object into a self-executing anonymous function. This is a tip I picked up from Cody Lindley’s excellent jQuery Enlightenment book.

Within our self-executing anonymous function add the rest of the code:

//object containing margin settings
var margins = {
	panel1: 0,
	panel2: -500,
	panel3: -1000,
	panel4: -1500,
	panel5: -2000
}

//handle nav click
$("#nav a").click(function(e){

	//stop browser default
	e.preventDefault();

	//remove on states for all nav links
	$("#nav a").removeClass("on");

	//add on state to selected nav link
	$(this).addClass("on");

	//set margin of slider to move
	$("#slider").animate({
		marginLeft: margins[$(this).attr("href").split("#")[1]]
	});
});

First of all we define a simple object that is used to hold the margin positions of each of the different panels; to show the first panel, the left margin of the #slider container should be at 0, to show the second panel it should be at -500px, and so on and so forth. Using an object like this is an easy way to store the values for each panel.

Next we add a click-handler for the navigation items; we want to show the panels using a nice animation so we have to prevent the browser from following the anchor. We do this using the event object (e) which we pass into our click-handler. The event object has the preventDefault() method built into it, so we call this on the event object and it stops the browser from executing its default action.

We use this part of the script to set the on class for the currently selected navigation item; this is the only part of the script that relies purely on JavaScript to function and simply removes the on class from any of the items on which it already exists, then adds back to the item that was clicked. There may be a way of doing this purely with CSS using the :active pseudo class, but as it is purely for a visual aid I don’t think it matters as much if this aspect doesn’t work with scripting disabled.

We now need to show the correct panel by animating the #slider container. Remember, we do this by setting the margin-left style property of the slider. In order to get the correct value for the marginLeft depending on whichever navigation link is clicked we just get the href attribute using the $(this) reference (which will point to whichever link was clicked) and perform a standard JavaScript split based on the # symbol.

We’re doing this the most semantic way – by using information we already have available, in this case the href attribute. We could add id attributes to each of the navigation links, but then we’re adding unnecessary extra information purely for our script which really we should avoid doing. Using the href makes sense but we can’t use # at the start of our object keys (panel1, panel2, etc) so we need to get rid of this character from the value that is returned.

Save the page and view it in your browser; you should find now that when one of the navigation items is clicked, the corresponding panel will slide smoothly into view. There’s just one more thing we need to do – the descriptive paragraphs don’t need to be visible all of the time (as long as JavaScript is enabled) so we can set these so that they are initially hidden from view and are shown when the content image is moused-over. We can add this behaviour easily using just a little bit more script; directly after the click-handler add the following code:

//hide descriptive text
$("#slider p").hide();

By hiding the paragraphs with JavaScript we ensure that the content is only hidden if scripting is enabled. This means that the content remains accessible even if JavaScript is disabled on the client. Next we just need to show the text when the main image is hovered over, to do that we can use jQuery’s hover() method; after the code we just added continue with the following:

//show descriptive text on mouseover (hide on mouseout)
$("#slider").hover(
	function() {
		$(this).find("p").slideDown();
	}, function() {
		$(this).find("p").slideUp();
});

All we do is use the slideDown() and slideUp() methods within the hover() method to show and hide the paragraphs when appropriate.

Summary

This now brings us to the end of this tutorial; we’ve seen how we should build our interfaces so that they work even when JavaScript is disabled, and that, instead of relying on JavaScript for functionality, we’re just relying on it to add attractive effects. We also saw that when we want to show content using JavaScript, such as the descriptive paragraphs, we first hide it using JavaScript so that it is only hidden when scripting is enabled which ensures the content is accessible even without scripting.

Your thoughts?

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 nettuts@tutsplus.com.

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

Write a PLUS tutorial


Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...