HV Designs » JQuery Tutorials http://www.hv-designs.co.uk Mon, 20 Apr 2015 11:52:33 +0000 en-US hourly 1 http://wordpress.org/?v=4.1.7 jQuery Menu w/ Drop Down Tutorial http://www.hv-designs.co.uk/2011/05/30/jquery-menu-w-drop-down-tutorial/ http://www.hv-designs.co.uk/2011/05/30/jquery-menu-w-drop-down-tutorial/#comments Mon, 30 May 2011 12:14:36 +0000 http://www.hv-designs.co.uk/jquery-menu-w-drop-down-tutorial/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Before 2006, it was not possible to make transitions, animations and other decent web stuff quickly within seconds. You will find a lot of plugins for menus, banners, etc. for the jQuery.

With the same purpose, my today’s tutorial is about a menu which has all the decent and stylish animated functionality, what you may be looking for. I’ll not go into details of HTML and CSS, I’m assuming you know about that or you can copy the HTML and CSS from below.

Slicing PSD

We have a free PSD for this tutorial and we’re using that in our tutorial, scroll down to download the PSD. Following is the snapshot how we will slice out.

slicing PSD

The HTML Structure

As you can see in the PSD, there are Menu items and one Search Bar on right side. The HTML for all those elements goes here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<div class="main-navigation">
    <ul>
        <li><a href="#">Home</a>
            <ul>
                <li><a href="#">Sub Menu Item 1</a></li>
                <li><a href="#">Sub Menu Item 2</a></li>
                <li><a href="#">Sub Menu Item 3</a></li>
                <li><a href="#">Sub Menu Item 4</a></li>
                <li><a href="#">Sub Menu Item 5</a></li>
            </ul>
        </li>
        <li><a href="#">Services</a>
            <ul>
                <li><a href="#">Sub Menu Item 1</a></li>
                <li><a href="#">Sub Menu Item 2</a></li>
                <li><a href="#">Sub Menu Item 3</a></li>
                <li><a href="#">Sub Menu Item 4</a></li>
                <li><a href="#">Sub Menu Item 5</a></li>
            </ul>
        </li>
        <li><a href="#">Portfolio</a>
            <ul>
                <li><a href="#">Sub Menu Item 1</a></li>
                <li><a href="#">Sub Menu Item 2</a></li>
                <li><a href="#">Sub Menu Item 3</a></li>
                <li><a href="#">Sub Menu Item 4</a></li>
                <li><a href="#">Sub Menu Item 5</a></li>
            </ul>
        </li>
        <li><a href="#">Contact</a>
            <ul>
                <li><a href="#">Sub Menu Item 1</a></li>
                <li><a href="#">Sub Menu Item 2</a></li>
                <li><a href="#">Sub Menu Item 3</a></li>
                <li><a href="#">Sub Menu Item 4</a></li>
                <li><a href="#">Sub Menu Item 5</a></li>
            </ul>
        </li>
    </ul>
    <div class="search">
        <input type="text" name="search" class="search-input" />
        <input type="submit" name="search" value="" class="search-btn" />
    </div>
</div>

Keep in mind I’ve added sub menus within the list item.

The CSS

Below is the CSS which used to format the menu. Apply the styles and see results in browser.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
.main-navigation{
    width:890px;
    height:44px;
    border:1px dashed #a2d2cf;
    background:url(../images/nav-bg.jpg) left repeat-x;
    top:50%;
    left:50%;
    margin:-22px 0 0 -445px;
    position:absolute;
    }
ul{
    margin:0px;
    padding:0px;
    list-style:none;
    }
li{
    float:left;
    font-size:15px;
    color:#FFFFFF;
    height:42px;
    display:block;
    position:relative;
    }
li .hover{
    color:#FFFFFF;
    text-decoration:none;
    position:absolute;
    background:url(../images/hover-bg.png) top left no-repeat;
    top:0;
    left:0;
    z-index:0;
    height:44px;
    display:none;
    }
li a{
    display:block;
    color:#FFFFFF;
    text-decoration:none;
    padding:14px 43px 13px 44px;
    z-index:1000;
    position:relative;
    }
.search{
    float:right;
    margin:9px 26px 0 0;
    padding:0px;
    }
.search-input{
    font-family:LucidaGrande, Lucida Sans, Arial;
    font-size:12px;
    color:#FFFFFF;
    width:117px;
    height:26px;
    padding:0 5px 0 10px;
    padding:5px 5px 0 10px \9;/* IE 7 and 8 */
    border:0;
    outline:none;
    background:url(../images/search-input-bg.png) top left no-repeat;
    float:left;
    }
.search-btn{
    width:37px;
    height:26px;
    border:0;
    outline:none;
    background:url(../images/search-btn.png) top left no-repeat;
    float:left;
    }
ul li ul{
    width:200px;
    position:absolute;
    display:none;
    top:44px;
    padding:1px 0 0 0;
    }
ul li:hover ul{
    display:block;
    }
ul li ul li{
    display:block;
    padding:10px 10px 10px 0;
    width:200px;
    padding:0px;
    margin:0px;
    background:url(../images/nav-bg.jpg) left repeat-x;
    position:relative;
    }
ul li ul li a{
    display:block;
    color:#FFFFFF;
    text-decoration:none;
    padding:14px 43px 13px 28px;
    z-index:1000;
    position:relative;
    }

Now you can view a decent looking menu with search box. You can check it’s functionality, it’s simple. Now we go ahead and work with jQuery to apply some effects to look it more decent. Here is the CSS menu snapshot.

CSS XHTML View

The jQuery

Now, the actual part of tutorial begins here. I will teach you step by step here. Go to the head section of your page and paste the following code.

1
2
3
4
5
6
7
<script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
});
</script>

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

I’ve included jQuery library from google libraries. After that, a normal script is started and in the //

After this, we will go for another function. That will do the same as we use some mouseover and mouseout functions. Let’s see the code.

1
2
3
4
5
$("li").hover(function() {
    //This function will call the HOVER event on any li.
} , function() {
    //This function will call the HOVER OUT event on the li which was hovered.
});

A basic function is ready and we will add all the transitions for menu here.

1
2
3
4
var itemwidth = $(this).width(); /* Getting the LI width */
$(this).prepend("<div class='hover'></div>"); /* Inserting a blank div into within li above the <a> tag*/
$(this).find("div").fadeIn('10000').css({ 'width' : itemwidth}); /* Using the itemwidth for the div to display properly*/
$(this).find("ul").fadeIn('1000').slideDown('10000').css("display", "block");

After putting the above code into HOVER function, our code will look like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("li").hover(function() {
var itemwidth = $(this).width(); /* Getting the LI width */
$(this).prepend("<div class='hover'></div>"); /* Inserting a blank div into within li above the <a> tag*/
$(this).find("div").fadeIn('10000').css({ 'width' : itemwidth}); /* Using the itemwidth for the div to display properly*/
$(this).find("ul").fadeIn('1000').slideDown('10000').css("display", "block");
} , function() {
    //This function will call the HOVER OUT event on the li which was hovered.
});
});
</script>

Now, we will work down the HOVER OUT event. Remove the HOVER OUT comments and put the following code in it.

1
2
3
$(this).find("div").slideUp('1000').fadeOut('1000');/* sliding up and fading out the hover div */
$(this).find("div").remove();/* removing the <div> code from html at every mouseout event*/
$(this).find("ul").fadeOut('1000'); /* fading out the sub menu */

Well. If you test the menu, it’s really amazing drop down and hover effects. The menu part has been done. We will go ahead and work on the animation of search box.

We will create two functions here. Focus and Focus out. Both are as follows:

1
2
3
4
5
6
7
$(".search-input").focus(function(){
$(this).animate({width:'180px'}, 500); /* on focus, increasing the input width of search to left side*/
    });
$(".search-input").focusout(function(){
    $(this).animate({width:'117px'}, 500);  /* on focus, decreasing the input width of search to left side*/
    });

Your jQuery menu including sub menu and search box are ready to use.

Conclusion

There are thousands of jQuery plugins available to use but the purpose of this tutorial is to give you a detailed practice how the jQuery work and how it creates animation in no time. I hope you will like the menu and give us feedback.

Download PSD FILE

 

ENjoy

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2011/05/30/jquery-menu-w-drop-down-tutorial/feed/ 0
Simple jQuery/CSS3 Modal Box http://www.hv-designs.co.uk/2011/03/20/simple-jquerycss3-modal-box/ http://www.hv-designs.co.uk/2011/03/20/simple-jquerycss3-modal-box/#comments Sun, 20 Mar 2011 12:14:44 +0000 http://www.hv-designs.co.uk/simple-jquerycss3-modal-box/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Seeing as how my last tutorial about the “jQuery slide effect” had a great response I thought I’d be back to write another simple easy-to-follow jQuery tutorial for you guys.

What we’ll be making today is a jQuery modal box which can be used can used for all sorts including images, forms and in my case, my blogging profile.

The Live Demo

You can view the Live Demo Here

What Makes This Effect

  • HTML
  • CSS3
  • jQuery
  • Dreamweaver (or your favorite text editor)

New document

For the purpose of this tutorial I will include all css and jQuery in one file (index.html) but would advise not to do so when using this script in a live website, always call you styles and jQuery from an external file.

With that done and said, create yourself a new html file and name it index.html

Calling jQuery

I like to use google’s jQuery, it’s useful if your user has already visited a site using google hosted jQuery as it’ll be cached on their machine already.

So, in your document inside the head section insert the following script tag.

1
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"><!--mce:0--></script>

Some markup

We’ll start by creating our modal box, using only on div to contain our elements such a heading, a few paragraphs and some social media icons. You can use the images included in the download or simply link to my online images.

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="modal-profile">
<h2>Nam liber tempor cum soluta nobis eleifend</h2>
    <a class="modal-close-profile" title="Close profile window" href="#"><img src="close.png" alt="Close profile window" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit littera um formas humanitatis per seacula quarta decima et quinta decima.Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
    <a class="modal-social" href="http://www.klevermedia.co.uk"><img src="http://www.klevermedia.co.uk/themes/klevermedia/images/social/lovedsgn.png" alt="Love design" /></a>
    <a class="modal-social" href="http://www.klevermedia.co.uk"><img src="http://www.klevermedia.co.uk/themes/klevermedia/images/social/forrst.png" alt="Forrst" /></a>
    <a class="modal-social" href="http://www.klevermedia.co.uk"><img src="http://www.klevermedia.co.uk/themes/klevermedia/images/social/twitter.png" alt="Love design" /></a>
    <a class="modal-social" href="http://www.klevermedia.co.uk"><img src="http://www.klevermedia.co.uk/themes/klevermedia/images/social/skype.png" alt="Love design" /></a>
    <a class="modal-social" href="http://www.klevermedia.co.uk"><img src="http://www.klevermedia.co.uk/themes/klevermedia/images/social/rss.png" alt="Love design" /></a></div>

Style the modal box

With the barebones of the modal box set up, it’s time to bring it to life with some styling. We’re going to be using a little bit off css3 to give our modal box some nicely rounded corners and a box shadow, as in most cases internet explorer doesn’t recognise the css rule “border-radius” and will show squared corners instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
.modal-profile h2 {
    font-size:2em;
    letter-spacing:-1px;
}
.modal-profile {
    display:none;
    height: 250px;
    width: 500px;
    padding:25px;
    border:1px solid #fff;
    box-shadow: 0px 2px 7px #292929;
    -moz-box-shadow: 0px 2px 7px #292929;
    -webkit-box-shadow: 0px 2px 7px #292929;
    border-radius:10px;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    background: #f2f2f2;
    z-index:50;
}
a.modal-close-profile {
    position:absolute;
    top:-15px;
    right:-15px;
}
a.modal-social {
    margin:0 10px 0 0;
}

-moz-box-shadow
Allows mozilla firefox to recognise the box shadow property

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

-webkit-box-shadow
Allows google chrome to recognise the box shadow property

-moz-border-radius
Allows mozilla firefox to recognise the border radius property

-webkit-border-radius
Allows google chrome to recognise the border radius property

Lights out

To create the block overlay on the body of our webpage once the modal box is opened we’ll be creating an effect known as “lights out”, quite self explanatory as it give the illusion of flicking the light switch off on our webpage.

Create a new div below our modal box with the class of “modal-lightsout” like so.

1
<div class="modal-lightsout"></div>

Thats’s it, just one div, simple right?

Now to apply some css to position the div and apply a black background (you could use white for this tutorial if you have a lighter website).

1
2
3
4
5
6
7
8
9
.modal-lightsout {
    display:none;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    z-index:25;
    background:#000;
}

Make it pop with jQuery

Now with all our markup and styles set it’s time to make things work with the help of jQuery. Apply this code in your head section below you google jQuery reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript">
$.fn.center = function () {
        this.css("position","absolute");
        this.css("top", ( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() + "px");
        this.css("left", ( jQuery(window).width() - this.width() ) / 2+jQuery(window).scrollLeft() + "px");
        return this;
      }
    $(".modal-profile").center();
    $('.modal-lightsout').css("height", jQuery(document).height());
    $('a[rel="modal-profile"]').click(function() {
        $('.modal-profile').fadeIn("slow");
        $('.modal-lightsout').fadeTo("slow", .9);
    });
    $('a.modal-close-profile, .modal-lightsout').click(function() {
        $('.modal-profile').fadeOut("slow");
        $('.modal-lightsout').fadeOut("slow");
    });
</script>

Creating the link

Our modal box is now complete and ready for action, all it takes is us to create a link to call it. It’s important that for any link we want to use our modal box we apply the “rel” name of “modal-profile” like this.

1
<a rel="modal-profile" href="#">Open modal box</a>

Simples!

This was just a basic and simple way of creating a modal box, there are plenty of other ways to do this I just thought I’d show you how I do mine. As stated, this is great to use as a profile pop-up, or be a little more creative and show us what you’ve done? Hope you’ve enjoyed the read.

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2011/03/20/simple-jquerycss3-modal-box/feed/ 0
jQuery Slide Effect http://www.hv-designs.co.uk/2010/10/20/jquery-slide-effect/ http://www.hv-designs.co.uk/2010/10/20/jquery-slide-effect/#comments Wed, 20 Oct 2010 12:13:14 +0000 http://www.hv-designs.co.uk/jquery-slide-effect/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

In today’s tutorial we are going to learn how to make a cool looking slide effect using jQuery that will really make our images pop.

The Live Demo

Click HERE to see the full working demo.

What makes this effect

html
css
jQuery

Dreamweaver (or your favourite text editor)

Setting up our files

Ok let’s start by opening our text editor and creating a new html document, save this to your desktop as “index.html”. Now create a new css file and save this as “style.css” in a new folder named “css”.

Include our files

Getting back to our index file, we now need to include our newly created css file and the jQuery library into the head of our document.

1
<link href="style.css" rel="stylesheet" type="text/css" />

In this tutorial we are going to link to the google api version of jQuery as the chances are your user has come across this file at some point so it was already be cached on their system. You can alternatively host your own version and link to it which you can download here.

1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

The mark up

Now we’ve included our necessary files for this effect to work let’s get dow to adding some html to our document. Include this html inside the <body> tag of the index file.

1
2
3
4
5
6
7
8
<div id="container">
<div id="overlay">
</div>
<div id="hover">
</div>
</div>

Style the body

Open up the css file we created earlier named “style” and let’s add some style to the page just to make it a little less bland. You can mess around with these colours as much as you like, it’s all down to preference really.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
body {
background-color:#1e1e1e;
padding-top:150px;
font-size:11px;
font-family:Arial, Helvetica, sans-serif;
}
h1 {
font-size:12px;
font-weight:bold;
color:#4de2e0;
}
a {
color:#4de2e0;
text-decoration:none;
}

Container style

Now the page has a little colour we can add the style to our divs, we’re going to start with the #container div this way we can talk through the reason for having certain styles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#container {
width:450px;
height:150px;
position:relative;
overflow:hidden;
z-index:0;
margin:0 auto;
background-image:url(1.png);
border:10px solid #414141;
}
#container:hover {
border-color:#303030;
}

The container is the div that displays our image, which the two other divs (#hover and #overlay) will slide over.

Position
We set this to relative because we need to set the child divs as absolute so that we position them our of view – this is an important style.

Overflow
This style basically hides the two child dives which gives the effect of them sliding across the image.

z-index
Places the div at the bottom of the pile which gives us the transparent look from the div above.

Overlay style

This is the div which ill give us the semi-transparent black effect that fades in over our image, let’s add the styles again to our css file and go through some of the important styles.

1
2
3
4
5
6
7
8
9
10
#overlay {
background-color:#000;
display:block;
position:absolute;
top:0;
left:0;
width:450px;
height:150px;
z-index:1;
}

background-colour
We can change this colour to what ever we would like the effect to be, for example #fff for white.

display
As the div is an empty one we need to display it as block.

position
We set this as absolute so that we can position it anywhere we like in our container that’s positioned as relative.

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

top and left
This will place are div at the very top and very left of our container div, we will change the left position using jQuery later.

z-index
We’ve set this as 1 so that it sits on top of our image.

Hover style

Now let’s add the styles for our final div #hover, which contains the content in our sliding effect.

1
2
3
4
5
6
7
8
9
10
11
12
13
#hover {
width:400px;
display:block;
height:100px;
position:absolute;
z-index:3;
padding:25px;
}
#hover p {
color:#fff;
font-weight:normal;
}
  1. Width and height, you may have noticed we’ve reduced our width and height here – reasons being we want to use padding so that our content isn’t squashed in.
  2. position, we’ve positioned this div as absolute again so that we can control where we place in in our container div.

Dummy content

You can place whatever you like in your div but for now I’m just going to place in some dummy content.

1
2
3
4
5
<h1>Cool hovering slide effect!</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
<p><a href="#"> Read more</a></p>

This goes inside the #hover div.

Let’s get down to the jQuery

Now for the fun stuff, we can start to animate our content using a little bit of jQuery. To do so we need to insert an opening and closing script tag in the head section of our document.

1
2
3
4
5
6
7
<script type="text/javascript">
$(document).ready(function () {
});
</script>

What is document ready?

Basically, what we’re doing here is telling our code not to run unless the document has fully loaded and ready to do so. Alternatively we can put our jQuery in our the just above our closing body tag in the footer which will automatically let the page load before running our script, which means we can remove our document.ready function all together.

Set the variables

The reason for setting variables in our code here is really just to save repeating code, which in this case is very useful.

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
$(document).ready(function () {
var colour = $("#overlay");
var content = $("#hover");
});
</script>

Hiding our divs

If you’ve previewed the code we have written so far you will have noticed that the divs just all sit on top of each other hiding our image which is not good. To get around this we will need to hide these elements using jQuery, let’s put those variables to use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type=”text/javascript”>
$(document).ready(function () {
var colour = $("#overlay");
var content = $("#hover");
content.hide();
colour.hide();
});
</script>

You will now notice that all we see is our image which is great.

Hover in some colour

Now we’re going to put our #overlay div to some use and fade in it and then back out again. Add the following code directly above the </script> tag.

1
2
3
4
5
6
7
8
9
10
11
$("#container").hover(function() {
colour.stop().fadeTo(500, .7)
}
,function() {
colour.stop().fadeTo(500, 0)
});

Time for a little explanation, the “500″ in the code represents how fast the div will fade in – in this case it will fade in at 500 milliseconds. We can change the opacity of the div to be stronger or weaker by adjusting the “.7″ currently this means the div will fade in to 70% opacity.

Slide in the content

To give our animation the full effect we’re going to need to get that div containing our content to start sliding in and out, take a look at this code and copy in lines and copy in lines 2 and 6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$("#container").hover(function() {
content.show().css({ "left” : “-450px" }).animate({left : 0}, 300);
colour.stop().fadeTo(500, .7)
}
,function() {
content.animate({left : 450}, 300);
colour.stop().fadeTo(500, 0)
});

.css() explanation

You can see here we’ve added some css to the #hover div, where we positioned the div as absolute earlier in our stylesheet we can now play around with this in our jQuery. Notice that the position left is minus (-) the full width of our div which will make place the this element just out of the visible portion of our container div, if you’re going to make you divs a different size to the one’s we have used in this tutorial you will need to adjust this part of the jQuery to match your new widths.

Stop our slider going mad

If your move the mouse frantically over the image you will notice that the content just keeps on sliding back and forth uncontrollably, to get over this we need to call in .stop() which will basically stop our code from over running. You may have noticed we already have this in place in the line controlling the colour fade, we’re basically going to do the same thing here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$("#container").hover(function() {
content.stop().show().css({ "left" : "-450px" }).animate({left : 0}, 300);
colour.stop().fadeTo(500, .7)
}
,function() {
content.stop().animate({left : 450}, 300);
colour.stop().fadeTo(500, 0)
});

Take a look for yourself now and see the difference.

A big thanks

Thank you for following this tutorial and I hope it comes of some use to you, feel free to contact me via my website (Klever media) if you have any questions or just leave a comment, any suggestions welcome.

VIEW DEMO

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2010/10/20/jquery-slide-effect/feed/ 0
Learn How To Create A Scrollable Website http://www.hv-designs.co.uk/2010/05/27/learn-how-to-create-a-scrollable-website/ http://www.hv-designs.co.uk/2010/05/27/learn-how-to-create-a-scrollable-website/#comments Thu, 27 May 2010 12:14:16 +0000 http://www.hv-designs.co.uk/learn-how-to-create-a-scrollable-website/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Good evening all, today were going to be diving into some jquery. What we’ll be creating is a small low key website which scrolls down to each section when a navigation item is clicked.

 

The Live Demo

Click the image to see the full working demo.

jQuery Scroll Live Demo

Resources Needed In This Tutorial

Lets get started…

Slicing The Images From Pre-Made PSD File

Before we start create a new folder on your desktop called template, inside the template folder create a further 3 folders. Label the 3 folders “Images”, “Js” and “Stylesheets”.

Next download the pre-made PSD file then open it up in photoshop. The PSD should look like this.

jQuery Scroll

We need to slice 3 items from the PSD file which will make up our demo, the rest can be done in CSS. The items we need to slice are “The Background”, “The Title” and “The Graphic Top”.

Using the “Rectangular Marquee Tool” make a selection around each item then save them inside the images folder. Be sure to put each image on a transparent background and save the files as “bg.png”, “title.png” and “top.png”.

jQuery Scroll

Creating The HTML Markup

Inside your template folder create a blank HTML file then inside your stylesheets folder create a blank CSS file. Once you’ve created the files open up both files inside your favorite code editor.

Inside your HTML file start the mark-up, which looks like this.

 <div id="top">  <div id="title"> </div><!--title ends-->  <div id="navigation"> </div><!--navigations ends-->  <div id="homepage"> </div><!--homepage ends-->  <div id="about"> </div><!--about ends-->  <div class="top"> </div><!--top ends-->  <div id="gallery"> </div><!--gallery ends-->  <div class="top"> </div><!--top ends-->  <div id="portfolio""> </div><!--portfolio ends-->  <div class="top"> </div><!--top ends-->  <div id="contact""> </div><!--contact ends-->  <div class="top"> </div><!--top ends-->  </div><!--container ends-->

Lets look at the mark-up abit more closer.

  • DIV Top – The div top is our container div, this div will be the div which holds all the elements to our layout. You’ll be pleased to know that there is also a reason why its labeled as “top”.When we click “Back To Top” which will be a link underneath each section the animation will scroll to the top of this div called “top”.
  • DIV Title – The div title will simply be a div which will house our title image.
  • DIV Navigation – This div will be the div in which our navigation will sit.
  • DIV’s Homepage, About, Gallery, Portfolio and Contact – These div’s are the sections in which the animation will scroll down to when the desired item is click in the navigation.
  • Class Top – The classes top in between each section will house our fancy separators and contain our “Back To Top” link.

jQuery Scroll

Adding Our Elements

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Inside the “Title” div insert your title.png image.

 <div id="title"> <img src="images/title.png" alt="jQuery Animated Scroll" /> </div><!--title ends-->

Inside the “Navigation” div create a simple unordered list for your navigation items. Each link should contain the class “Scroll”, this class is needed for the scroll animation to work. Also take note of the hyperlinks in each navigation item, the hyperlinks are actually the names of the DIV’s in which are used in the HTML code.

 <div id="navigation"> <ul> <li><a href="#about" class="scroll">About Me</a></li> <li><a href="#gallery" class="scroll">Gallery</a></li> <li><a href="#portfolio" class="scroll">Portfolio</a></li> <li><a href="#contact" class="scroll">Contact Me</a></li> </ul> </div><!--navigations ends-->

Inside each of the sections “Homepage, About, Gallery, Portfolio and Contact” insert a H1 tag which will contain the section title. Also inside the H1 tag add a description of that section wrapped in a span class.

 <div id="homepage"> <h1>Homepage <br /> <span class="description">This is the Homepage</span></h1> </div><!--homepage ends-->  <div id="about"> <h1>About <br /> <span class="description">This is the About Page</span></h1> </div><!--about ends-->  <div class="top"> </div><!--top ends-->  <div id="gallery"> <h1>Gallery <br /> <span class="description">This is the Gallery Page</span></h1> </div><!--gallery ends-->  <div class="top"> </div><!--top ends-->  <div id="portfolio"> <h1>Portfolio <br /> <span class="description">This is the Portfolio Page</span></h1> </div><!--portfolio ends-->  <div class="top"> </div><!--top ends-->  <div id="contact"> <h1>Contact <br /> <span class="description">This is the Contact Me Page</span></h1> </div><!--contact ends-->  <div class="top"> </div><!--top ends-->

Finally inside the classes “Top” add a simple P tag containing the words “Back To Top”, add a link to the words which should link to our top div. Don’t forget to add the class “Scroll” to the link, without this jquery wont work.

 <div id="homepage"> <h1>Homepage <br /> <span class="description">This is the Homepage</span></h1> </div><!--homepage ends-->  <div id="about"> <h1>About <br /> <span class="description">This is the About Page</span></h1> </div><!--about ends-->  <div class="top"> <p><a href="#top" class="scroll">Back To Top</a></p> </div><!--top ends-->  <div id="gallery"> <h1>Gallery <br /> <span class="description">This is the Gallery Page</span></h1> </div><!--gallery ends-->  <div class="top"> <p><a href="#top" class="scroll">Back To Top</a></p> </div><!--top ends-->  <div id="portfolio"> <h1>Portfolio <br /> <span class="description">This is the Portfolio Page</span></h1> </div><!--portfolio ends-->  <div class="top"> <p><a href="#top" class="scroll">Back To Top</a></p> </div><!--top ends-->  <div id="contact"> <h1>Contact <br /> <span class="description">This is the Contact Me Page</span></h1> </div><!--contact ends-->  <div class="top"> <p><a href="#top" class="scroll">Back To Top</a></p> </div><!--top ends-->

Adding The CSS

The CSS for all our elements look like this.

 body { background-image: url(../images/bg.gif); background-repeat: repeat-x; background-color: #FFFFFF; margin: 0px; padding: 0px; font-family: Verdana, Arial, Helvetica, sans-serif; }  #top { width: 950px; margin-top: 50px; margin-right: auto; margin-bottom: auto; margin-left: auto; }  #title { margin: auto; width: 495px; clear: both; }  #navigation { float:left; width:100%; overflow:hidden; position:relative; margin-top: 20px; margin-bottom: 20px; }  #navigation ul { clear:left; float:left; list-style:none; margin:0; padding:0; position:relative; left:50%; text-align:center; }  #navigation ul li { display:block; float:left; list-style:none; margin:0; padding:0; position:relative; right:50%; }  #navigation ul li a { display:block; margin:0 0 0 1px; padding:3px 10px; color:#666666; text-decoration:none; line-height:1.3em; }  #navigation ul li a:hover { color:#000000; }  #navigation ul li a.active, #navigation ul li a.active:hover { color:#000000; font-weight:bold; }  #homepage { float: left; width: 950px; height: 800px; }  #about, #gallery, #portfolio, #contact { float: left; width: 950px; height: 600px; }  h1 { color: #5a5a5a; font-size: 24px; font-weight: normal; margin: 0px; padding: 0px; }  span.description { color: #9f9f9f; font-size: 12px; }  .top { background-image: url(../images/top.png); background-repeat: no-repeat; float: left; height: 48px; width: 950px; padding-bottom: 35px; background-position: bottom; margin-bottom: 20px; }  .top p { text-align: center; color: #999999; font-size: 10px; }  a:link { color: #666666; } a:visited { color: #666666; } a:hover { color: #000000; } a:active { color: #666666; }

Adding The jQuery

Download the latest jQuery library from the jQuery website, place the library file inside your “JS” folder.

Next, open up notepad then go to “File > Save As” save the blank notepad file as “Scroll.js” inside your “JS” folder.

Open up your “Scroll.JS” file inside your code editor then paste the following snippet inside and save.

 $(document).ready(function(){ $(".scroll").click(function(event){ //prevent the default action for the click event event.preventDefault();  //get the full url - like mysitecom/index.htm#home var full_url = this.href;  //split the url by # and get the anchor target name - home in mysitecom/index.htm#home var parts = full_url.split("#"); var trgt = parts[1];  //get the top offset of the target anchor var target_offset = $("#"+trgt).offset(); var target_top = target_offset.top;  //goto that anchor by setting the body scroll top to anchor top $('html, body').animate({scrollTop:target_top}, 500); }); });

Test your HTML file inside your browser and see how it works.

That’s it all done hope you enjoyed this tutorial.

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2010/05/27/learn-how-to-create-a-scrollable-website/feed/ 0
Jquery Fade In, Fade Out Effect – Updated http://www.hv-designs.co.uk/2010/01/13/learn-how-to-add-a-jquery-fade-in-and-out-effect/ http://www.hv-designs.co.uk/2010/01/13/learn-how-to-add-a-jquery-fade-in-and-out-effect/#comments Wed, 13 Jan 2010 12:13:47 +0000 http://www.hv-designs.co.uk/jquery-fade-in-fade-out-effect-updated/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Hello welcome to another tutorial by hv-designs, today we’ll be re-visiting the “jQuery Fade In, Fade Out Effect” that i posted up earlier last year. There was no point updating the old post as it is over a year old, so here’s the new one.

 

Dont Know jQuery?

Dont worry its real simple to use and implement. If you really want to get stuck into jquery then nettuts have wrote a complete series on the subject SEE THIS LINK.

Whats jQuery?

Firstly whats jquery? i hear you ask, well jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

What can i do with this code your about to give me? Basically its a fade in fade out effect. The effect fades an element to 50% on arrival of the website, then when you hover over it, it fades to 100%. The effect can be assigned to basically anything in a website wether it be an image, text, a link or even a div.

New Revised Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$(function() {
// OPACITY OF BUTTON SET TO 50%
$("ELEMENT HERE").css("opacity","0.5");
// ON MOUSE OVER
$("ELEMENT HERE").hover(function () {
// SET OPACITY TO 100%
$(this).stop().animate({
opacity: 1.0
}, "slow");
},
// ON MOUSE OUT
function () {
// SET OPACITY BACK TO 50%
$(this).stop().animate({
opacity: 0.5
}, "slow");
});
});

The code is pretty much the same as the last snippet only this time is contains some “stop” functions which stops the transition from repeating over and over again. This seemed to be major problem with the last tutorial.

Adding The Effect Into Your Website

Now im going to show you how to add this all into your website. Ive put together a small download which contains a simple example.

Extract the contents of “example_one.zip” to your desktop, inside the folder “example one” create a new folder called “js”. Then inside the “js” folder place the jquery libary file which can be found here.

Create a blank notepad file then go to “file > save as”, save the blank notepad file inside the “js” folder called “custom.js”. Inside the “js” folder there should be 2 files. “jquery1.3.min.js” and “custom.js”.

Open up the custom.js file in dreamweaver then copy and paste the jquery effect code into the document, then save.

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

You should be all set to go, just a couple of things to take note of. If you look inside the HTML code of the example you will notice inside the HEAD tags there are some lines of javascript.

1
2
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/custom.js"></script>

Its basically the same as linking a .CSS file only its javascript. Without this bit of HTML code jquery wont work. Make sure the filenames of the .js files match yours, i do believe you need to change the 1st one from “jquery” to “jquery-1.3.min.js”.

The Effect

Now for the effect, as i said before you can use the effect on almost anything inside of a HTML document, now we want to add the effect to the individual images we have in our example HTML file, if you look at the code in the HTML file regarding the images you will notice they have a class of “class=”latest_img”.

The class is defined in the .CSS file. The class is a form of ID in which the images can be identified by. If we open up “custom.js” in dreamweaver then locate the words “ELEMENT HERE” inside two quotes, change “ELEMENT HERE” to the class which is “.latest_img” the effect will apply its self to everything with a class of “latest_img” in our case the images. Your .js code should look like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$(function() {
// OPACITY OF BUTTON SET TO 50%
$(".latest_img").css("opacity","0.5");
// ON MOUSE OVER
$(".latest_img").hover(function () {
// SET OPACITY TO 100%
$(this).stop().animate({
opacity: 1.0
}, "slow");
},
// ON MOUSE OUT
function () {
// SET OPACITY BACK TO 50%
$(this).stop().animate({
opacity: 0.5
}, "slow");
});
});

Save it, then view your HTML file in your browser. The effect should have been applyed to the single images. See Demo.

More Demo’s

Pretty cool ah?, Now the effect doesnt stop there as you can apply it to other things within an HTML document, how about applying it to some text? See Demo.

The text within my HTML document is in P tags within a div so if i apply the effect to the p tag within a certain div you get the effect above. You can also apply the effect to a whole div, which means everything in that div will fade even the div itself. See Demo.

Here are all the effects on one page.

Why dont you try and incorparate the fade in fade out effect in your designs, or just play around and see what you can come up with ;)

Thanks for reading

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2010/01/13/learn-how-to-add-a-jquery-fade-in-and-out-effect/feed/ 0
jQuery UI Accordion Widget Pt.2 http://www.hv-designs.co.uk/2009/09/08/jquery-ui-accordion-widget-pt2/ http://www.hv-designs.co.uk/2009/09/08/jquery-ui-accordion-widget-pt2/#comments Tue, 08 Sep 2009 12:13:33 +0000 http://www.hv-designs.co.uk/jquery-ui-accordion-widget-pt-2/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

The accordion widget is a robust and highly configurable widget that allows you to save space on your web pages by only displaying a certain section of related content at any one time.

This is like a tabbed interface but positioned vertically instead of horizontally. It’s easy for your visitors to use and it’s easy for us to implement. It has a range of configurable properties that can be used to customize its appearance and behaviour. It also has a series of methods that allow you to control it programmatically.

In the previous part of this article, we looked at the structure of an accordion widget and its configurable properties. In this second part , we will cover the following topics:

– Built-in types of animation –
– Custom accordion events –

Accordion Animation

You may have noticed the default slide animation built into the accordion. Apart from this, there are two other built-in animations that we can easily make use of. We can also switch off animations entirely by supplying false as the value of the animated property, although this doesn’t look too good!

The other values we can supply are bounceslide and easeslide. However, these aren’t actually unique animations as such. These are different easing styles which don’t change the animation itself but instead, alter the way it runs. You should note at this stage that additional jQuery plugins are required for these easing methods.

For example, the bounceslide easing method causes the opening drawer to appear to bounce up and down slightly as it reaches the end of the animation. On the other hand, easeslide makes the animation begin slowly and then builds up to its normal speed. Let’s take a moment to look at these different easing methods now. Change accordion11.html so that it appears as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span>
<span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple click!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum
pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est.
Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div>
</div>
<div><a href="#">Header 3</a><div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed
quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus. </div>
</div>
</div>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/jquery.easing.compatibility.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//set custom easing
var accOpts = {
animated: "bounceslide"
}
//turn specified element into an accordion
$("#myAccordion").accordion(accOpts);
});
</script>

Save this file as accordion12.html. We’ve used a couple of new script files in the source code. The jquery.easing.1.3.js file is the latest version of the easing plugin, and the jquery.easing.compatibility.js plugin which enables the latest version of the easing file to work without any further modifications. The easing type names were renamed in version 1.2 of the easing plugin. Both of these files can be found on the jQuery site.

The built-in easing effects, based on a series of equations created by Robert Penner in 2006, are very easy to use and create a great effect which can help build individuality into accordion implementations

Plugins:
There are many jQuery plugins available. These are often developed by the open-source community instead of the library’s authors and can be used with jQuery and jQuery UI. A good place to find plugins is on the jQuery site itself. Some of these plugins, such as the easing plugin, work with the library components, while other plugins, such as the compatibility plugin, assist other plugins.

Accordion Events

The accordion defines the custom change event which is fired after a drawer on the accordion opens or closes. To react to this event, we can use the change configuration property to specify a function to be executed every time the event occurs. In a new file in your text editor, add the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span>
<span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div id="panel1">Wow, look at all this content that can be shown or hidden with a simple click!</div>
</div>
<div><a href="#">Header 2</a><div id="panel2">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed
interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est.
Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div></div>
<div><a href="#">Header 3</a><div id="panel3">Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero.
Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div>
</div>
</div>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//define config object
var accOpts = {
//add change event callback
change: function(e, ui) {
alert($(ui.newContent).attr("id") + " was opened, " + $(ui.oldContent).attr("id") + " was closed");
}
};
$("#myAccordion").accordion(accOpts);
});
</script>

Save this as accordion13.html. In this example, we use the change configuration property to specify an anonymous callback function which is executed every time the event is triggered. This function will automatically receive two objects as arguments. The first object is the event object which contains information about the event. The second object is an object containing useful information about the accordion widget, such as the content drawer that just opened or closed.

In the mark-up for the accordion, we have given each of the content drawer “div” elements an id attribute which can be used in the alert generated by the change callback. We can use the ui.newContent and ui.oldContent properties to obtain the relevant content drawer and display its id in the alert.

The accordion widget also defines the accordion change event which is fired after a drawer on the accordion opens or closes. To react to this event, we can use the standard jQuery bind() method to specify a callback function, just like with the tabs widget.

Fun With Accordion

Let’s put a sample together that will make the most of the accordion widget and uses some of the properties and methods that we’ve looked at so far in both the parts of this article. A popular implementation of accordion is as a navigation menu. Let’s build one of these based on the accordion widget. The following screenshot shows the finished page.

08

In a new page in your text editor, create the following HTML file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  <div id="container">
   <div id="navCol">
    <ul id="navAccordion">
     <li>
      <a class="heading" href="#me" title="About Me">About Me</a>
      <div>
        <a href="bio.html#me" title="Bio">My Bio</a>
        <a href="contact.html#me" title="Contact Me">Contact Me</a>
        <a href="resume.html#me" title="Resume">My Resume</a>
      </div>
    </li>
    <li>
     <a class="heading" href="#js" title="JavaScript">JavaScript</a>
    <div>
     <a href="tutorials.html#js" title="JavaScript Tutorials">JavaScript Tutorials</a>
     <a href="ajax.html#js" title="AJAX">AJAX</a>
     <a href="apps.html#js" title="JavaScript Apps">JavaScript Apps</a>
    </div>
   </li>
   <li>
    <a class="heading" href="#css" title="CSS">CSS</a>
    <div>
     <a href="layouts.html#css" title="Layouts">Layouts</a>
     <a href="themes.html#css" title="Themes">Themes</a>
     <a href="hacks.html#css" title="Hacks">Hacks</a>
    </div>
   </li>
  </ul>
 </div>
<div id="contentCol">
  <h1>A jQuery UI Accordion Navigation Example!</h1>
  <p>This is the starting page for this example, when you click on either of the accordion headings at the left,
  an accordion drawer containing a set of links will open. Clicking on a link will take you to a new page, which will
  look exactly like this one but will have different text on it.</p>
  </div>
  <div id="clear"></div>
  </div>
   <script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
   <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
   <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
   <script type="text/javascript">
   //function to execute when doc ready
   $(function() {
      //turn specified element into an accordion
   $("#navAccordion").accordion({
      header: ".heading",
      event: "mouseover",
      autoHeight: false,
      alwaysOpen: false,
      active:false,
      navigation: true
   });
 });
   </script>

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Save this as navAccordion.html. To see the full effects of the navigation property, the other pages that the main page links to should be available.

We use a selection of configurable properties in this example. The header property allows us to target only the links that have the class name heading. This prevents the links in the content sections from picking up any header attributes. We make use of the event property again to specify mouse over as the trigger event.

Switching off the autoHeight property prevents unnecessary whitespace in the menu from showing if there is one content section with much more content in it than other sections. The alwaysOpen property allows all headings to be closed. Disabling the active property also allows the page to load with all headings closed which is helpful if someone is visiting the application for the first time.

In order to make the most of the navigation property in this example, we make sure that all the links that lead to new pages also include a fragment identifier matching the href of their heading element. Therefore, when a new page opens the state of the menu is maintained.

We’ll also need some CSS for this example, just to make the page and the accordion look as we want them to. In a new file in your text editor, add the following stylesheet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* page */
#clear { clear:both; }
#container { border:1px solid #4e82b4; width:601px; }
#navCol {
  width:230px; height:287px; float:left; background-color:#a1d2f6;
}
#contentCol {
  width:310px; height:227px; float:left; background-color:#ffffff; padding:30px; border-left:1px solid #4e82b4;
}
h1 { margin:0px; font:bold 14px Verdana; }
#contentCol p { margin:20px 0 0 0; font:normal 11px Verdana; }
/* accordion */
#navAccordion {
  list-style-type:none; padding-left:0; text-align:right; margin:20px 0 0 0; width:231px; position:relative; left:0;
}
#navAccordion a {
  display:block; text-decoration:none; font:bold 11px Verdana; color:#000000; padding:0 40px 0 0; padding-bottom:5px;
}
#navAccordion a:hover { text-decoration:underline; }
#navAccordion a.heading {
  font:bold 24px Verdana; color:#ffffff; border-bottom:1px dashed #4e82b4; padding:0 30px 10px 0;
}
#navAccordion a.heading:hover { text-decoration:none; }
 .selected, #navAccordion .selected a.heading {
  background-color:#ffffff; color:#000000; border-top:0; border-bottom:1px solid #4e82b4; border-right:1px solid #ffffff;
  border-left:1px solid #ffffff;
}
#navAccordion .selected a.heading { border:0; }
#navAccordion li { margin:0; }
#navAccordion li span, #navAccordion li a { background-image:none; }
#navAccordion li span { display:none; }

Save this as navAccordionTheme.css in the styles folder. The page and CSS code is kept as minimal as possible, although a certain minimum amount of coding is going to be required in any practical example.

If you run navAccordion.html in your browser now, and then click on any of the links within each content section, you’ll navigate to a new page. Thanks to the navigation:true name:value pair, the relevant section of the accordion will be open when the new page loads as seen below.

 

08

Summary

In this article we looked at accordian’s default animation and saw how we can add simple transition effects to the opening of content drawers. Accordion widget is a flexible and robust widget that provides essential functionality and interaction in an aesthetically pleasing way.

Liked This Article? Why Not Buy The Book

Build highly interactive web applications with ready-to-use widgets of the jQuery user interface library.

Buy The Book

Learn More…

 

 

Enjoy

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2009/09/08/jquery-ui-accordion-widget-pt2/feed/ 0
jQuery UI Accordion Widget Pt.1 http://www.hv-designs.co.uk/2009/08/30/jquery-ui-accordion-widget-pt1/ http://www.hv-designs.co.uk/2009/08/30/jquery-ui-accordion-widget-pt1/#comments Sun, 30 Aug 2009 12:13:31 +0000 http://www.hv-designs.co.uk/jquery-ui-accordion-widget-pt-1/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

In this article by packt publishing we’ll be looking into a jQuery UI Accordion Widget. The accordion widget is another UI widget made up of a series of containers for your content, all of which are closed except for one.

Therefore, most of its content is initially hidden from view. Each container has a heading element associated with it, which is used to open the container and display the content. When you click on a heading, its content is displayed. When you click on another heading, the currently visible content is hidden while the new content is shown.

It should be noted that the height of the accordion’s container element will automatically be set so that there is room to show the tallest content panel in addition to the headers. This will vary, of course, depending on the width that you set on the widget’s container.

Accordion’s Structure

Let’s take a moment to familiarize ourselves with what an accordion is made of. Within the outer container is a series of links. These links are the headings within the accordion and each heading will have a corresponding content panel, or drawer as they are sometimes referred to, which opens when the heading is clicked. The following screenshot shows these elements as they may appear in an accordion.

Step1

It’s worth remembering that when using the accordion widget, only one content panel can be open at any one time. Let’s implement a basic accordion now. In a blank page in your text editor, create the following page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<ul id="myAccordion">
<li>
<a href="#">Header 1</a>
<div>Wow, look at all this content that can be shown or hidden with a simple click!</div>
</li>
<li>
<a href="#">Header 2</a>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpatligula. Integer
vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut
bibendum velit enim eu lectus. Suspendisse potenti. </div>
</li>
<li>
<a href="#">Header 3</a>
<div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc. Pellentesque tincidunt viverra felis.
Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div>
</li>
</ul>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion();
});
</script>

Save the file as accordion1.html in your jqueryui folder and try it out in a browser. We haven’t specified any styling at all at this stage, but as you can see from the following screenshot, it still functions exactly as intended.

 

Step2

Little code is required for a basic working version of the accordion widget. A simple unordered list element is the mark-up foundation which is transformed by the library into the accordion object.

The following three separate external script files are required for an accordion:

– The jQuery library itself (jquery-1.2.6.js) –
– The UI base file (ui.core.js) –
– The accordion source file (ui.accordion.js) –

The first two files are mandatory requirements of all components of the UI library. They should be linked to in the order shown here. Each widget also has its own source file, and may depend on other components as well.

The order in which these files appear is important. The jQuery library must always appear first, followed by the UI base file. After these files, any other files that the widget depends upon should appear before the widget’s own script file. The library components will not function as expected if files are not loaded in the correct order.

Finally, we use a custom “script” block to turn our “ul” element into the accordion. We can use the jQuery object shortcut $ to specify an anonymous function which will be executed as soon as the document is ready. This is analogous to using $(document).ready(function(){}) and helps to cut down on the amount of code we have to type.

Following this, we use the simple ID selector $(“#myAccordion”) to specify the element on the page we want to transform. We then use the accordion() constructor method to create the accordion

Other elements can be turned into accordions as well. All list element variants are supported including ordered lists and definition lists. You don’t even need to base the accordion on a list element at all. You can build a perfectly functional accordion using just nested “div” and “a” elements, although additional configuration will be required

In the above example, we used an empty fragment (#) as the value of the href attribute. You should note that any URLs supplied for accordion headers will not be followed when the header is clicked within the accordion when using the default implementation.

Styling The Accordion

With no styling, the accordion will take up 100% of the width of its container. Like with other widgets, we have several options for styling the accordion. We can create our own custom stylesheet to control the appearance of the accordion and its content, we can use the default or flora themes that come with the library, or we can use Theme Roller to create an extensive skin for the whole library. Let’s see how using the flora theme for the accordion will cause it to render. In accordion1.html, add the following “link” tag to the “head” of the page.

 <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.accordion.css">

Save the new file as accordion2.html, also in the jqueryui folder, and view it again in a browser. It should appear something like this.

Step3

The accordion theme file assumes that an unordered list is being used as the basis of the widget and specifically targets “li” elements with certain style rules. We can easily create our own custom theme to style the accordion for situations where we want to use a non-list-based accordion widget, or if we simply want different colors or font styles.

You can use the excellent Firebug plugin for Firefox, or another DOM viewer, to see the class names that are automatically added to certain elements when the accordion is generated. You can also read through an un-minified version of the source file if you really feel like it. These will be the class names that we’ll be targeting with our custom CSS.

The following screenshot shows Firebug in action.

Step4

Change accordion2.html so that it appears as follows (new code is shown in bold).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple click!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam
iaculis volutpatligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum,
turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div></div>
<div><a href="#">Header 3</a><div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc.
Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div></div>
</div>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion();
});
</script>

Save this version as accordion3.html in the jqueryui folder. The class name ui-accordion is automatically added to the accordion’s container element. Therefore, we can use this as a starting point for most of our CSS selectors. The links that form our drawer headers are given the class ui-accordion-header so we can also target this class name. In a new file, create the following stylesheet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#myAccordion {
 width:200px;
 border:2px solid #000000;
 position:relative;
 list-style-type:none;
 padding-left:0;
}
.ui-accordion-header {
 text-decoration:none;
 font-weight:bold;
 color:#000000;
 display:block;
 width:100%;
 text-align:center;
}
.ui-accordion div div {
 font-size:90%;
}
.ui-accordion a {
 color:#ffffff;
 background:url(../img/accordion/header-sprite.gif) repeat-x 0px 0px;
}
.ui-accordion a.selected {
 background:url(../img/accordion/header-sprite.gif)
 repeat-x 0px -22px;
}
.ui-accordion a:hover {
 background:url(../img/accordion/header-sprite.gif)
 repeat-x 0px -44px;
}
/* container rounded corners */
.corner {
 position:absolute;
 width:12px; height:13px;
 background:url(../img/accordion/corner-sprite.gif) no-repeat;
}
.topLeft {
 top:-2px; left:-2px;
 background-position:0px 0px;
}
.topRight {
 top:-2px; right:-2px;
 background-position:0px -13px;
}
.bottomRight {
 bottom:-2px; right:-2px;
 background-position:0px -26px;
}
.bottomLeft {
 bottom:-2px; left:-2px;
 background-position:0px -39px;
}

Save this file as accordionTheme.css in your styles folder and preview accordion3.html in a browser. We will need a new folder for the images we use in this and subsequent examples. Create a new folder inside the img folder and name it accordion. With just two images, and a few simple style rules, we can drastically change the default appearance of the accordion with our own custom skin as shown in the following screenshot.

 

Step5

Configuring The Accordion

The accordion has a range of configurable properties which allow us to easily change the default behaviour of the widget. The following table lists the available properties, their default value, and gives a brief description of their usage.

Configuring The Accordion

Configurable properties The configurable properties for all of the different components of jQuery UI are constantly evolving with each new release of the library. You can keep track of the latest properties by looking through the online jQuery UI API pages. Each component has its own page and can be accessed from jQuery Docs

Most of the properties are self-explanatory, and the values they accept are usually booleans, strings, or element references. Let’s put some of them to use so we can explore their functionality. Alter accordion3.html so that it appears as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple mouseover!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum
pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris
at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div></div>
<div><a href="#">Header 3</a><div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed
quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div></div>
</div>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//set the event property
var accOpts = {
event:"mouseover"
}
//turn specified element into an accordion
$("#myAccordion").accordion(accOpts);
});
</script>

First, we create a new object literal called accOpts which contains one property key and a value. We then pass this object into the accordion() constructor as an argument, and it overrides the default properties of the widget. The string we specified for the value of the event property becomes the event that triggers the activation of the drawers, making this a very useful property. Save the changes as accordion4.html.

You should note that you can also set properties using an inline object within the widget’s constructor method without creating a separate object (see accordion4Inline.html). Using the following code would be equally as effective, and would often be the preferred way for coding.

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion({
event:"mouseover"
});
});
</script>

We can set other properties at the same time as well. If we want to change which drawer is open by default when the accordion is rendered, as well as change the trigger event, we would supply both properties and the required values, with each pair separated by a comma. Update accordion4.html so that it appears as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a id="header1" href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple mouseover!</div></div>
<div><a id="header2" href="#">Header 2</a><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed
interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut
posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div></div>
<div><a id="header3" href="#">Header 3</a><div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices
libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div></div>
</div>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//configure accordion
var accOpts = {
event:"mouseover",
active:"#header3"
}
//turn specified element into an accordion
$("#myAccordion").accordion(accOpts);
});
</script>

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

The first change is to give our header elements id attributes in the underlying HTML in order to target them with the active property. In our object literal, we then specify the selector for the header we would like to open by default. Save the file as accordion5.html. When the page is opened, the third drawer should be displayed by default.

The other properties listed in the table at the start of this section are equally as easy to configure. Change the object literal so that it appears as follows.

1
2
3
4
5
6
7
//configure accordion
var accOpts = {
event:"mouseover",
active:"#header3",
alwaysOpen:false,
autoHeight:false
}

Save these changes as accordion6.html and view the results in a browser. First, you should find that when you first roll over a heading the drawer opens as normal, but the accordion grows or shrinks depending on how much content is in the drawer. It no longer stays at a fixed height. This can be seen in the following example.

 

Step6

You should also find that if you roll over a heading whose drawer is already open, the drawer will close and the accordion will shrink so that only the headers are displayed with no open drawers. Note that when using false with the alwaysOpen property, the accordion will shrink in this way regardless of whether the autoHeight property is set to true or false.

Step7

The fillSpace property, if set, will override autoHeight. You should also be aware that the clearStyle property will not work with autoHeight. One final property we should look at is the navigation property. This property is used to enable navigating to new pages from accordion headings. Change accordion6.html to this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a id="header1" href="#1">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple mouseover!</div></div>
<div><a id="header2" href="#2">Header 2</a><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed
interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut
posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div></div>
<div><a id="header3" href="#3">Header 3</a><div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices
libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div></div>
</div>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//configure accordion
var accOpts = {
event:"mouseover",
active:"#header3",
alwaysOpen:false,
autoHeight:false,
navigation:true
}
//turn specified element into an accordion
$("#myAccordion").accordion(accOpts);
});
</script>

Save the changes as accordion7.html. When you roll over one of the headings, they will still open as normal, but if you click on one of the headings, the URL specified as the header’s href attribute will be followed.

With navigation enabled, the widget will check for a fragment identifier at the end of the URL when the page loads. If there is a fragment identifier, the accordion will open the drawer whose heading’s href attribute matches the fragment. So, if the second heading is clicked in this example, and then the page is refreshed, the second drawer of the accordion will be opened automatically. Therefore, it is important to ensure that the href attributes for each accordion header is unique to avoid conflicts in this situation.

Accordion Methodology

The accordion includes a selection of methods that allow you to control and manipulate the behavior of the widget programmatically. Some of the methods are common to each component of the library, such as the destroy method, which is used by every widget. We’ll look at each of these methods in turn.

Destruction

One method provided by the accordion is the destroy method. This method removes the accordion widget and returns the underlying mark-up to its original state. We’ll use the default properties associated with accordion instead of the ones we configured for the last few examples. In a new page in your text editor, add the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple click!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed
interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut
posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti.</div></div>
<div><a href="#">Header 3</a><div>Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc.
Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div></div>
</div>
<button id="accordionKiller">Kill it!</button>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion();
//attach click hander to button
$("#accordionKiller").click(function() {
//destroy the accordion
$("#myAccordion").accordion("destroy");
});
});
</script>

The “body” of the page contains a new “button” element, which can be used to destroy the accordion. The final “script” block also contains a new anonymous function. We use the standard jQuery library’s click() method to execute some code when the targeted “button” element is clicked.

We use the same accordian() constructor method to destroy it as we did to create it. But this time, we supply the string “destroy” as an argument. This causes the class names added by the library to be removed, the opening and closing behavior of the headers to no longer be effective, and all of the previously hidden content will be made visible.

Because we used an ID selector in our theme file to style the accordion container, this element will retain its size and borders. The roll-over effects were added by targeting the class names created by the library. As these are removed, along with the rest of the accordion’s functionality, the rollovers do not activate. Save this file as accordion8.html.

Enabling and disabling

Two very simple methods to use are enable and disable. These are just as easy to use as destroy, although they do have some subtle behavioral aspects that should be catered for in any implementation as you’ll see. Change accordion8.html to the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple click!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum...</div></div>
<div><a href="#">Header 3</a><div>Donec at dolor...</div></div>
</div>
<button id="enable">Enable!</button><button id="disable">Disable!</button>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion();
//add click handler for enable button
$("#enable").click(function() {
//enable the accordion
$("#myAccordion").accordion("enable");
});
//add click handler for disable button
$("#disable").click(function() {
//disable the accordion
$("#myAccordion").accordion("disable");
});
});
</script>

We use these two methods in exactly the same way as the destroy method. Simply call accordion() with either enable or disable supplied as a string parameter. Save this file as accordion9.html and try it out.

One thing you’ll quickly notice is that when the accordion has been disabled, the rollover and selected effects are still apparent. This could be misleading as there is no visual cue that the widget has been disabled. This behavior is sure to be fixed in a later revision of the library. But for now, we can easily fix this with a little standard jQuery goodness and apply disabled states ourselves.

Another problem we have with our test page is that clicking the Enable! button while the accordion is already enabled does nothing. There is, of course, nothing for it to do. Some kind of indication that the widget is already enabled would be helpful. Let’s see how easy it is to fix these minor issues. Update the current page to this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple click!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum...</div></div>
<div><a href="#">Header 3</a><div>Donec at...</div></div>
</div>
<button id="enable">Enable!</button><button id="disable">Disable!</button>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion().addClass("enabled");
//add click handler for enable button
$("#enable").click(function() {
//alert if already enabled, enable and change classes if not
($("#myAccordion").hasClass("enabled")) ? alert("Accordion already enabled!") : $("#myAccordion").accordion("enable").addClass("enabled").removeClass("disabled") ; });
//add click handler for disable button
$("#disable").click(function() {
//alert if already disabled, disable and change classes if not
($("#myAccordion").hasClass("disabled")) ? alert("Accordion already disabled!") : $("#myAccordion").accordion("disable").addClass("disabled").removeClass("enabled") ;  });
});
</script>

The new code takes care of notifying the visitor if they click the Enable! button while the accordion is already enabled, or if the Disable! button is clicked while it is already disabled, through simply adding two additional class names; enabled and disabled

We use the standard jQuery addClass() method to initially set an additional class name of enabled on the accordion’s container. A simple JavaScript ternary then looks for the presence of this class and invokes the alertif it is detected. This is done using the jQuery hasClass() method.

If the accordion is changed from enabled to disabled, the addClass(), and also the removeClass() methods are used to swap our class names appropriately. A less intrusive way for us to do this, without the need for alerts, would be to actually disable the Enable! button while the accordion is enabled and vice-versa. I’ll leave you to try this on your own.

Save this as accordion10.html. Now we can add some new styles to our stylesheet to address our new disabled class. Open accordionTheme.css in your text editor and add the following new selectors and rules after the existing ones.

1
2
3
4
5
6
7
8
9
10
11
12
13
/* disabled state */
.disabled a {
 background:url(../img/accordion/disabled.gif) repeat-x 0px 0px;
 cursor:default;
}
.disabled a.selected {
 background:url(../img/accordion/disabled.gif) repeat-x 0px 0px;
 cursor:default;
}
.disabled a:hover {
 background:url(../img/accordion/disabled.gif) repeat-x 0px 0px;
 cursor:default;
}

Save this as accordionTheme2.css (don’t forget to update the link to the stylesheet in the “head”). Now, when the Disable! button is clicked, the new class name will pick up our grayed out headings. As we’ve specified the same background image for the selected and hover states, the accordion will not appear to respond in any way to clicks or mouse overs while disabled.

Drawer Activation

The final method exposed by accordion is the activate method. This can be used to programmatically show or hide different drawers. We can easily test this method using a text box and a new button. Change acordion10.html to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id="myAccordion">
<span class="corner topLeft"></span><span class="corner topRight"></span><span class="corner bottomLeft"></span><span class="corner bottomRight"></span>
<div><a href="#">Header 1</a><div>Wow, look at all this content that can be shown or hidden with a simple click!</div></div>
<div><a href="#">Header 2</a><div>Lorem ipsum... </div></div>
<div><a href="#">Header 3</a><div>Donec at... </div></div>
</div>
<p>Choose a drawer to open</p>
<input id="choice" type="text"><button id="activate">Activate</button>
<script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script>
<script type="text/javascript" src="jqueryui1.6rc2/ui/ui.accordion.js"></script>
<script type="text/javascript">
//function to execute when doc ready
$(function() {
//turn specified element into an accordion
$("#myAccordion").accordion();
//add click handler for activate button
$("#activate").click(function() {
//get the value from the text box
var choice = $("#choice").val();
//open the chosen drawer
$("#myAccordion").accordion("activate", choice - 1);
});
});
</script>

Save this file as accordion11.html. The activate method is used in the same way as the destroy method. It is passed to the accordion() constructor as an argument. Apart from supplying the string “activate”, we also need to tell the accordion which drawer to activate using a number representing the drawer’s index.

Like standard JavaScript arrays, the index numbers for the accordion drawer headings begin with zero. Therefore, to open the correct drawer, we subtract 1 from the figure entered into the text box when we call the activate method.

Summary

The accordion widget allows us to easily implement an object on the page which will show and hide different blocks of content. This is a popular, and much sought after, effect which is implemented by big players on the web today like Apple.

We first saw that the accordion widget doesn’t require any CSS at all in order to function as the behaviour without styling still works perfectly. We also looked at the flora styling, as well as the ease in which custom styles can be added.

We then moved on to look at the configurable properties that can be used with accordion. We saw that we can use these properties to change the behaviour of the widget, such as specifying an alternative heading to be open by default, whether the widget should expand to fill the height of its container, or the event that triggers the opening of a content drawer.

In addition to looking at these properties, we also saw that there are a range of methods which can be called on the accordion to make it do things programmatically. For example, we can easily specify a drawer to open, enable and disable any drawers, or even completely remove the widget and return the mark-up to its original state.

In the next and final part of this article, we will take a look at Built-in types of animation and Custom accordion events.

 

Liked This Article? Why Not Buy The Book

Build highly interactive web applications with ready-to-use widgets of the jQuery user interface library.

Buy The Book

Learn More…

 

Enjoy

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2009/08/30/jquery-ui-accordion-widget-pt1/feed/ 0
How to Add Flair to your Actions with jQuery http://www.hv-designs.co.uk/2009/08/10/how-to-add-flair-to-your-actions-with-jquery/ http://www.hv-designs.co.uk/2009/08/10/how-to-add-flair-to-your-actions-with-jquery/#comments Mon, 10 Aug 2009 12:14:45 +0000 http://www.hv-designs.co.uk/how-to-add-flair-to-your-actions-with-jquery/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

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 class="label">Text Size</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Bigger</button>
<button id="switcher-small">Smaller</button>
</div>
<div class="speech">
<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:

01

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 class=”speech” 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:

 

02

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 class="label">Text Size</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Bigger</button>
<button id="switcher-small">Smaller</button>
</div>
<div class="speech">
<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="#" class="more">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:

 

03

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:

 

04

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:

 

05

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:

 

06

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.

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

.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:

 

07

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: http://www.wpdfd.com/issues/78/absolutely_relative/
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:

08

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 http://docs.jquery.com/Effects.

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 class="label">Text Size</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Bigger</button>
<button id="switcher-small">Smaller</button>
</div>
<div class="speech">
<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="#" class="more">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:

 

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:

 

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.

 

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2009/08/10/how-to-add-flair-to-your-actions-with-jquery/feed/ 0
jQuery Sliding Panel http://www.hv-designs.co.uk/2009/06/05/jquery-sliding-panel/ http://www.hv-designs.co.uk/2009/06/05/jquery-sliding-panel/#comments Fri, 05 Jun 2009 12:13:50 +0000 http://www.hv-designs.co.uk/jquery-sliding-panel/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Hello welcome to another tutorial by hv-designs, in this tutorial we’ll be creating and coding a login form concealed within a sliding panel, the sliding panel itself will expand once clicked, revealing the content within.

 

The first thing you need to do is mockup your slide panel in photoshop, ive used the header from my gaming layout 6 tutorial. Ive replaced the top navigation bar with a thin grey bar about 2-3 pixels in height. Ive then created a button in the middle of the grey bar using the rounded rectangle tool. Heres what mine looks like.

Step1

For the purposes of this tutorial you may download and use the PSD ive created, you can download the PSD “HERE“. Create a new folder on your desktop called “what ever you want” inside this folder create another two folders called “images” and “js”. Open up a blank notepad document and goto “file > save as”, save the blank document as “styles.css” inside your main folder. Save another blank document as “panelslide.js” only this time save it inside your “js folder”.

Step2

Step2

Goto the main jquery website and download jquery, save the file into your “js” folder. Open up your favourite code editor and create a blank HTML file, save the file as index.html inside your main folder. Now lets link our css file and js files, place the following code into the head of your html document.

1
2
3
4
5
6
<!--STYLE SHEETS-->
<link href="styles.css" rel="stylesheet" type="text/css" />
<!--JS FILES-->
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/panelslide.js" type="text/javascript"></script>

Now lets begin to mark-up the top part of the website and the sliding panel, the mark-up is pretty short and sweet. Start off with a div of “container”, inside the div container add another div called “header”.

1
2
3
4
5
6
<div id="container"><!--CONTAINER STARTS-->
<div id="header"><!--HEADER STARTS-->
</div><!--HEADER ENDS-->
</div><!--CONTAINER ENDS-->

Inside the div header add another div id of “slide-panel”, all the content for the sliding panel should be inserted within the slide-panel div.

1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="container"><!--CONTAINER STARTS-->
<div id="header"><!--HEADER STARTS-->
<div id="slide-panel"><!--SLIDE PANEL STARTS-->
SLIDE PANEL CONTENT HERE
</div><!--SLIDE PANEL ENDS-->
</div><!--HEADER ENDS-->
</div><!--CONTAINER ENDS-->

Thats all we need for the markup, time for some CSS, for the purpose of this tutorial im going to code the header as one image, instead of coding it all seperate as we dont really need a proper search from etc.. Firstly lets create our image slices, your going to need a snippet of the background to apply as the body background, then your going to need an image of the header wthout the slide button. See images below.

 

Step3

Step4

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Your also going to need a single image of just the slide button without text.

Step5

You now should have 3 .PNG files inside your images folder.

Step6

Head over to your stylesheet and add the following styles. Please refer to the comments for each style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* MAIN BODY STYLES */
* {
    margin: 0px; /*NO MARGIN/*
    padding: 0px; /*NO PADDING*/
}
body {
    background-image: url(images/bg.png); /*BACKGROUND IMAGE*/
    background-repeat: repeat-x; /*REPEATS HORIZONTALLY*/
    background-color: #E6E6E6; /*SETS BACKGROUND COLOR*/
    margin: 0 auto; /*SETS TOP AND BOTTOM MARGIN TO 0. ALSO SETS LEFT AND RIGHT MARGIN TO AUTO*/
    padding: 0; /*NO PADDING*/
    font-family: Arial, Helvetica, sans-serif; /*SETS FONT FAMILY*/
    font-size: 75%; /*FONT SIZE*/
    line-height: 100%; /*LINE HEIGHT*/
}
#container {
    margin: auto; /*SETS MARGIN TO AUTO, THIS CENTER'S OUR WEBSITE*/
    width: 900px; /*CONTAINER WIDTH*/
}
#header {
    float: left; /*FLOATS HEAD LEFT*/
    height: 165px; /*HEIGHT OF HEADER IMAGE*/
    width: 900px; /*WIDTH OF WEBSITE*/
    background-image: url(images/header.png); /*OUR HEADER IMAGE*/
    background-repeat: no-repeat; /*STOPS HEADER IMAGE REPEATING*/
}

Once you’ve added the styles above you should now see your repeated background and your header image. You may need to adjust the height of the header div to the same height as your header image. We can now add the styles for our sliding panel, again refer to the commented code next to each style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* SLIDING PANEL STYLES */
#slide-panel {
    height: 200px; /*HEIGHT OF HIDDEN SLIDE PANEL*/
    width: 350px; /*WIDTH OF HIDDEN SLIDE PANEL*/
    display: none; /*THE ELEMENT WILL NOT BE DISPLAYED*/
    border-right-width: 2px; /*ADDS RIGHT BORDER OF 2PX*/
    border-left-width: 2px; /*ADDS LEFT BORDER OF 2PK*/
    border-right-style: solid; /*MAKES RIGHT BORDER SOLID*/
    border-left-style: solid; /*MAKES LEFT BORDER SOLID*/
    border-right-color: #626262; /*RIGHT BORDER COLOR*/
    border-left-color: #626262; /*LEFT BORDER COLOR*/
    background-color: #949494; /*SLIDE PANEL BACKGROUND COLOR*/
    border-bottom-width: 2px; /*ADDS BOTTOM BORDER OF 2PX*/
    border-bottom-style: solid; /*MAKES BOTTOM BORDER SOLID*/
    border-bottom-color: #626262; /*BOTTOM BORDER COLOR*/
    opacity: .8; /*SETS SLIDE PANEL BACKGROUND'S OPACITY TO 80%*/
    margin: auto; /*CENTERS OUR SLIDE PANEL*/
}
.slide {
    margin: 0; /*NO MARGIN*/
    padding: 0; /*NO PADDING*/
    background-image: url(images/slide_button.png); /*ADDS OUR BUTTON IMAGE*/
    background-repeat: no-repeat; /*STOPS BUTTON FROM REPEATING*/
    background-position: center top; /*SETS BUTTON POSITION*/
}
.btn-slide {
    text-align: center; /*ALIGNS TEXT CENTER*/
    width: 191px; /*BUTTON WIDTH*/
    height: 26px; /*BUTTON HEIGHT*/
    display: block; /*DISPLAY AS A BLOCK*/
    color: #fff; /*TEXT COLOR*/
    text-decoration: none; /*REMOVES UNDERSCORE FROM LINK*/
    font-family: Arial, Helvetica, sans-serif; /*FONT FAMILY*/
    font-weight: bold; /*TURNS TEXT BOLD*/
    font-size: 1em; /*FONT SIZE*/
    margin-right: auto; /*MARGIN AUTO*/
    margin-left: auto; /*MARGIN AUTO*/
    line-height: 22px; /*LINE HEIGHT OF BUTTON TEXT*/
}

The div “slide-panel” is our a panel the other two classes “slide & btn-slide” are for our slide button. Underneath the slide panel ending div in your HTML document add a P tag with a class of slide, add a HREF tag to the word login. Add a class of btn-slide to the link. Use a “#” for the link url.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div id="container"><!--CONTAINER STARTS-->
<div id="header"><!--HEADER STARTS-->
<div id="slide-panel"><!--SLIDE PANEL STARTS-->
SLIDE PANEL CONTENT HERE
</div><!--SLIDE PANEL ENDS-->
<p class="slide"><a href="#" class="btn-slide">Login</a></p><!--LOGIN BUTTON TEXT-->
</div><!--HEADER ENDS-->
</div><!--CONTAINER ENDS-->

You can also now add your content inside the slide panel div. Lets now connect it all together with jquery, the jquery code itself is pretty simple, open up your panelslide.js file and add the follwowing code.

1
2
3
4
5
6
7
$(document).ready(function(){
$(".btn-slide").click(function(){
$("#slide-panel").slideToggle("slow");
});
});

Your slide panel should now work, although for the opacity style to work in internet explorer we need to change the way the opacity style is written. We need to setup a new stylesheet just for internet explorer, open up a blank notepad document and save it as ie.css inside the main folder. Open up the ie.css document in your code editor and add the following style.

1
2
3
#slide-panel {
    filter: alpha(opacity=80); /*sets opacity of slide panel to 80%*/
}

We now need to link the file in our html file, in the head of the html file add this bit of code.

1
2
3
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

You will also need another style to work with internet explorer 8, you can either setup another style sheet or you can tell the internet explorer 8 browser to emulate internet explorer 7.

1
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

Your sliding panel should now be complete. Heres an example of it empty.

Heres an example with an example login form.

Hope you enjoyed this tutorial, dont forget to subscribe via RSS and twitter. Your support is much appreciated.

 

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2009/06/05/jquery-sliding-panel/feed/ 0
jQuery & jFlow http://www.hv-designs.co.uk/2009/05/27/jquery-jflow/ http://www.hv-designs.co.uk/2009/05/27/jquery-jflow/#comments Wed, 27 May 2009 12:13:46 +0000 http://www.hv-designs.co.uk/jquery-jflow/

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

Good evening everybody in todays tutorial we’ll be dabbling into some jquery. We’ll be intergrating a jQuery plugin called jFlow into a website.

 

Before we start this tutorial your going to need a few things:

– Jquery 1.2.6.Pack (download here).
– Jquery jFlow Plugin 1.0 (download here).
– A website ready template to add jflow into.

If you want to read up about the jflow plugin there website is HERE. If your asking yourself “why is he using jquery 1.2.6?” then the answer to your question is because i couldnt get jflow to work with the new libary. (just speaking from experience). Although i do believe there is a jflow 1.2 version which might work.

Once you have all your files open up your template in your code editor. Navigate to your templates main folder, create a new folder called “js” then copy and paste the jflow and jquery 1.2.6 file into the folder. Open up your index.html and link the two files in the head section by your style sheet.

1
2
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.flow.1.1.min.js" type="text/javascript"></script>

Underneath the two linked js files add this chunk of javascript.

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
$(function() {
$("div#controller").jFlow({
slides: "#slides",
width: "900px",
height: "250px"
});
});
</script>

Without the chunk of code above your slides will not slide. The width and height are required, if you remove the height the slides will work in firefox but will not in internet explorer. The width of my slides on my template are 900px wide and 250px in height, you will have to adjust these 2 values according to your own design. Lets look at the code above in more deatil.

Firstly we have a div of #myController this is the div where all the controllers will be nested. we then have a div of #slides this is the div where all your sliding divs are nested in. we then have width this can be specified in px or % as is a required style. We then have height this can be specified in px and is also required.

Lets take alook at my featured area in which we’ll be placing the slides. Il be using the “Your PROject” template i made in a previous tutorial. The code looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="featured"><!--FEATURED CONTENT STARTS-->
<div class="featured-text"><!--FEATURED TEXT STARTS-->
<h1 class="featured">featured text here 01</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus porttitor est et ante euismod vel euismod tortor ornare. Quisque turpis augue, iaculis vel luctus non, dapibus a ante. Quisque vitae turpis augue. Nulla facilisi.  Continue Reading...</p>
</div><!--FEATURED TEXT ENDS-->
<div id="featured-image01"><!--FEATURED IMAGE STARTS-->
<div class="featured-buttons"><!--NEXT AND PREVIOUS BUTTONS STARTS-->
<div class="featured-btn">
<img src="images/next_btn.png" alt="Next"  />
<div class="featured-btn"><img src="images/prev_btn.png" alt="Previous" />
</div>
</div>
</div><!--NEXT AND PREVIOUS BUTTONS END-->
</div><!--FEATURED IMAGE ENDS-->
</div><!--FEATURED CONTENT ENDS-->

The mockup above looks like this.

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

 

Step1

Above the featured area DIV tag we need to add our jflow controllers copy and paste the code below, above your featured area code.

1
2
3
4
5
<div id="controller" class="hidden">
<span class="jFlowControl">No 1</span>
<span class="jFlowControl">No 2</span>
<span class="jFlowControl">No 3</span>
</div>

My main featured area has a main container called featured, rename this to slides. Also rename the style in the style sheet to slides. At the very bottom of your style sheet we need to add the style to hide our other two slides. We can do this by adding the style below.

1
2
3
.hidden {
    display: none; /*hides our 2nd and 3rd featured slides*/
}

In our featured area under the slides div we need to add a blank div. At the end of our featured content we need to close the div. The code looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div id="slides"><!--FEATURED CONTENT STARTS-->
<div><!--STARTS SLIDE #1-->
<div class="featured-text"><!--FEATURED TEXT STARTS-->
<h1 class="featured">featured text here 01</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus porttitor est et ante euismod vel euismod tortor ornare. Quisque turpis augue, iaculis vel luctus non, dapibus a ante. Quisque vitae turpis augue. Nulla facilisi.  Continue Reading...</p>
</div><!--FEATURED TEXT ENDS-->
<div id="featured-image01"><!--FEATURED IMAGE STARTS-->
<div class="featured-buttons"><!--NEXT AND PREVIOUS BUTTONS STARTS-->
<div class="featured-btn">
<img src="images/next_btn.png" alt="Next"  />
<div class="featured-btn"><img src="images/prev_btn.png" alt="Previous" />
</div>
</div>
</div><!--NEXT AND PREVIOUS BUTTONS END-->
</div><!--FEATURED IMAGE ENDS-->
</div><!--ENDS SLIDE #1-->
</div><!--FEATURED CONTENT ENDS-->

Your next two slides or how ever many you will have to being with another empty div and end with a div so for example your slides would look like this.

1
2
3
4
5
6
7
8
9
10
11
<div><!--STARTS SLIDE #1-->
FIRST SLIDE CONTENT
</div><!--ENDS SLIDE #1-->
<div><!--STARTS SLIDE #2-->
SECOND SLIDE CONTENT
</div><!--ENDS SLIDE #2-->
<div><!--STARTS SLIDE #3-->
THIRD SLIDE CONTENT
</div><!--ENDS SLIDE #3-->

Inside our featured content area we also have two images, the images are a left and right arrow.

1
2
<div class="featured-btn"><img src="images/next_btn.png" alt="Next"  /></div>
<div class="featured-btn"><img src="images/prev_btn.png" alt="Previous" /></div>

On each button we need to add a new class associated with jflow. The classes are.

1
2
class="jFlowNext"
class="jFlowPrev"

The jFlowNext classes will make the slide go left, the jFlowPrev will slide the content right. We have to add both classes into our featured area. The next class will go on our next button and the prev class will go on our previous button. Like this.

1
2
<div class="featured-btn"><img src="images/next_btn.png" alt="Next" class="jFlowNext"  /></div>
<div class="featured-btn"><img src="images/prev_btn.png" alt="Previous" class="jFlowPrev" /></div>

Once you’ve done that upload your template and see how it looks. If you wanted to make it slightly easier to read in your code you could place each slide in a php file then include them into your template. To view the finished product click the button below.

Thats all, hope you’ve enjoyed this tutorial any problems dont hesitate to ask. The template will be free to download soon so keep your eyes peeled.

 

Your ads will be inserted here by

AdSense Now!.

Please go to the plugin admin page to paste your ad code.

]]>
http://www.hv-designs.co.uk/2009/05/27/jquery-jflow/feed/ 0