Wednesday, August 20, 2008

Starting With jQuery - Effects

This is second post in a string of posts where I chronicle my adventure in learning jQuery from having no previous experience with the framework.  Last week we did a quick crash course with jQuery to show how easy it was to create a fairly simple UI with only a few lines of code.  This week, we're going to play around with some of the visibility effects that it has to offer. Visibility effects are nothing more than ways to show, hide, and fade different elements on your web page.  While this may seem trivial, a quick look at sites such as the BBC and Google's iGoogle web portal provide examples of how being able to toggle visibility of certain parts of the web site can greatly enhance the user experience.

Unlike my previous post in this series, we only will need the primary jQuery.js file.  Once again, we're going to be using jQuery version 1.2.6, and the file can be downloaded here.

In addition to the jQuery.js file, a colleague inquired as to where I learned how to use jQuery and specifically the topic of this post. To be honest, I learned everything that I'm talking about through using jQuery's web site.  The documentation on the site is amazing to say the least and anyone who is interested in learning jQuery, I HIGHLY recommend checking out their site at jQuery.com.  In addition, there are a number of great people talking about jQuery and a quick searching on Live.com or Google yields enough results that can help guide you to answering any question you may find yourself having.  The jQuery documentation that covers what I'm covering in this post can be found here.

Now, for the quick look at the different things we can do with jQuery's effects.  To keep things simple, we're going to focus on basic, sliding, and fading effects.  jQuery allows for more advanced effects to be accomplished; however, I'm just going to keep things simple.

In order to do any of the effects you need 2 things; the jQuery.js file, and a web page with an element you wish to show and/or hide.  Sounds simple enough.

So, let's start with some simple HTML that has a simple <div> we will be playing with and a button to invoke the actions.

   1: <div id="header" style="width:100%; background-color:#800000; height:100px; display:block;">
   2: This area needs to disappear.
   3: </div>
   4: <br />
   5: <input type="button" value="Click Me!" /> 

We're just keeping it simple today.  Now, let's dive into the jQuery.

Basic Effects

The first thing we're going to look at with jQuery's visual effects will be to hide our <div> when we click on the button.  To do this, we simply call the jQuery element's hide() function.

   1: function visibilityHelper()
   2: {
   3:     $("#header").hide();
   4: }

After we add the function call to our button's onClick event handler, we see that the hide() function causes the <div> to be animated by sliding it up, left, and fading it out.  That's pretty cool for such a small amount of code.

In addition, to the default hide() function, the function can also include a parameter to control the speed of the animation.  In the example below, we add the speed and also call the show() function to make the element immediately reappear.

   1: function visibilityHelper()
   2: {
   3:     $("#header").hide("slow");
   4:     $("#header").show("slow");
   5: }

Now that we have seen how to hide and show elements, there are additional things we can do with these functions. Both functions have 2 possible parameters to alter the default behavior however you need. 

The first parameter the functions accept controls the speed of the animation (as shown in the previous code snippet).  This parameter can have 1 of 4 values; "slow", "normal", "fast", or a duration in milliseconds (e.g. 4000 would stretch the animation over 4 seconds).

The second parameter the functions take after speed is the ability to call another function once it has finished.  This callback can be very useful to do cascading animation, looping, or other page manipulations (i.e. AJAX Calls to populate content).

Let's modify our example to illustrate both of these parameters.  In the code below, we're setting the duration of our hide() function to "fast" and adding a call to another function which shows an alert box.

   1: function visibilityHelper()
   2: {
   3:     $("#header").hide("fast", function(){alert("Hidden")});
   4:     $("#header").show("slow");
   5: }

The last item in the basic effects is the toggle() function.  This function allows you to show and hide an element without having to keep track of the element's state.  Taking our code snippet that we used to just call the hide() function, we can replace it with toggle().  Now, every time we click on our button, the visibility of our <div> tag will change.

   1: function visibilityHelper()
   2: {
   3:     $("#header").toggle();
   4: }

Notice, toggle() provides no default animation and does not allow for you to adjust the speed nor call another function once finished.  This function is simply setting display:none; and then removing it for you.

Slide Effects

Sliding effects are very similar to the basics we just covered; however, there are a few differences. 

  • All Sliding Effects functions require the speed parameter
  • You can only Slide Up (hide the element) and Slide Down (show the element)

Sounds pretty simple overall.  Let's replace our toggle() function call from our last example with the slideUp("slow") function.

   1: function visibilityHelper()
   2: {
   3:     $("#header").slideUp("slow");
   4: }

In order to reveal an element after it is hidden, we can call the slideDown("speed") function in the same fashion as the show() function.

   1: function visibilityHelper()
   2: {
   3:     $("#header").slideUp("slow");
   4:     $("#header").slideDown("slow");
   5: }

In addition, sliding effects also supply a slideToggle("speed") function that allows us to toggle the element's visibility with the slide animation without having to monitor the element's state. 

   1: function visibilityHelper()
   2: {
   3:     $("#header").slideToggle("slow");
   4: }

Lastly, all 3 of the sliding effect functions have an optional parameter to allow for a function to be called once the animation has finished.

Fade Effects

The last set of effects for this post are the fade effects.  This set of effect functions allow the developer or designer show and hide elements by having them fade in and out of the page.  Just like the sliding effects, the fade effect functions all require the speed of the animation to be specified as illustrated below.

   1: function visibilityHelper()
   2: {
   3:     $("#header").fadeOut("slow");
   4:     $("#header").fadeIn("slow");
   5: }

In the code, we used the fadeOut("slow") and fadeIn("slow") functions to fade the element out and in respectively.  Like their sliding counterparts, they also have the optional parameters to call functions once the animation is finished.

Unlike basic and sliding effects, the fade effects do not have a toggle option.  Instead, fade effects get a special function called fadeTo().  This function requires 2 parameters, the duration of the animation, and the opacity value that the animation will fade to.  The opacity value is a decimal value between 0 and 1.00.  In addition to the 2 required parameters, an optional third is available to call a function when finished like the rest of the functions discussed in this post.  Below is a code example of using the fadeTo() function.

   1: function visibilityHelper()
   2: {
   3:     $("#header").fadeTo("slow", 0.50);
   4: }

One of the nice things about the fadeTo() function is that it provides a very simple way to control the opacity of elements across browsers without having to write a line of CSS.  This simplifies development for custom light boxes as well other common visuals seen on the Internet today.

Summary

My first thoughts while playing around with jQuery's effects was that it was a quick and simple way to add some simple animations to web pages that I've done by hand with some frustrations before.  After exploring the effects further and truly focusing on the effect applications further, I began to fully appreciate the power of these functions.

One effect set that I did not discuss in this post was the Advanced Effect Functions.  I have excluded them specifically because I'm still playing with them myself, and I want to make sure that I can provide accurate information on how to use such.  Again, the information found on jQuery's web site for effects is excellent and I highly encourage anyone wanting to learn more to check it out.

In the next post in this series, we'll be introduced to the jQuery Validation plug-in for easy client-side form validation.  Later on, I'll begin to provide examples on how to integrate jQuery into typical Asp.Net 2.0 applications and some of the challenges that a person may face.


kick it on DotNetKicks.com

IE7: Vista vs. XP

At the end of my post last week when I began a series on learning jQuery, I mentioned that I might have found a bug.  This bug involved columns at the bottom of last weeks demo to be rendered differently when I viewed the same code on my Windows XP computer and my Windows Vista computer.  At the time of the post, the images that you saw in last weeks post, were taken from my Windows XP computer and they looked fine in the browsers that I test in (IE7, IE8 beta 1, Opera, Firefox, and Safari).  When I looked at the code on my Vista box, the columns had a line break after each one even with the CSS property of display:inline-block; and float:left;.  

Since that post, I couldn't reproduce the problem so it probably was user error (it happens).  However, while I was researching this "bug" since it annoyed and mildly terrified me (I  didn't want to have to consider testing my web pages with IE7 on 2 different versions of Windows), I ran this Google search and it didn't help things.

Based on the search, it would appear that while my "bug" wasn't directly mentioned, the search did show that there appeared to be some differences in how IE7 renders pages and interprets JavaScript on XP and Vista.  I haven't ran into it prior to this.  While my bug is now non-reproducible, the knowledge that there may be a different was well worth my mistake.

So, has anyone heard or seen this issue?  I'd love to hear what everyone's experiences are.


kick it on DotNetKicks.com

Wednesday, August 13, 2008

Starting with jQuery

This is the first of number of posts to come on getting started with jQuery with no previous knowledge of the framework.  Over the course, various jQuery Plug-Ins will be used and discussed along with gradual integration with traditional ASP.Net 2.0 web applications components (i.e. Master Pages, User Controls, and ASP.Net AJAX).

A few days ago, I was approached at work to research some of the popular JavaScript frameworks out there.  I've looked at a number of different frameworks in the past, and I wasn't too impressed with the complexity and learning curve with them at that time.  Well time has passed since then, and I've grown fond of examining what some major companies are using on their web sites.  Looking out across the landscape, there's a large number of frameworks out there such as Prototype, Dojo, Spry, and YUI.

Combining this research with my company's request, I began to notice that some of the sites that I frequent use jQuery.  The things that appeals the most to me about jQuery was it's small foot print, the number of community based plug-ins that have been created, and the amount of examples and documentation on the web site to get a person up and running in no time.  If you spend a little time on the site, you'll begin noticing items like "jQuery for Designers" which makes me think that it should be pretty simple overall.  Granted some of the best designers can cut some of the best code, but not too many from my experience.  Regardlesss, this seemed like a perfect choice; however, this was partly for work so I needed to dig deeper and do a test run.

For any initial UI research, I tend to try to keep things simple.  For such this time, I used Expression Web instead of Visual Studio 2005 or 2008.  In order to begin using jQuery for this example, I downloaded the following items:

  • jQuery v1.2.6 minimized - link
  • jQuery v1.2.6 Uncompressed - link
  • Center Element Plug-in (trying to keep CSS compliant) - link
  • Rounded Corners Plug-in (for aesthetics) - link

So, I wanted a simple UI with a Header, Navigation, Body, and 3 Footer Columns.  Below is the HTML:

   1: <body>

   2: <div id="container">

   3:     <div id="header" class="rounded">

   4:         This is the Header</div>

   5:     <div id="navigation" class="rounded">

   6:         This is the Navigation

   7:     </div>

   8:  

   9:     <div id="form" class="rounded">

  10:         <form id="testForm">

  11:         <input name="btnTest" type="button" value="Show/Hide Header" onclick="toggleHeader();" /><br />

  12:         <br />

  13:         <label for="txtName" class="inputLabel">First Name: </label><input name="txtName" type="text" id="txtName" title="Please Enter a First Name" /><br />

  14:         <label for="txtLastName" class="inputLabel">Last Name :</label><input name="txtLastName" type="text" id="txtLastName" class="textOnly" title="Please Enter a Last Name" /><br />

  15:         <label for="txtAddress1" class="inputLabel">Address:</label><input name="txtAddress1" type="text" id="txtAddress1" class="addressField" title="Please Enter an Address" /><br />

  16:         <input name="txtAddress1" type="text" id="txtAddress2" class="addressField" title="Please Enter an Address" /> <br />

  17:         <input name="btnValidate" type="submit" value="Validate Name" id="btnValidate" />

  18:         </form>

  19:     </div>

  20:     <div id="leftColumn" class="columns">left

  21:     </div>

  22:     <div id="centerColumn" class="columns">center

  23:     </div>

  24:     <div id="rightColumn" class="columns">right

  25:     </div>

  26: </div>

  27: </body>



And now for a little bit of CSS styling...




   1: #header {

   2:     color: #FFFFFF;

   3:     background-color: #800000;

   4:     margin: 5px 10px 5px 10px;

   5:     padding-bottom: 36px;

   6:     height: 75px;

   7: }

   8: #container {

   9:     height: 750px;

  10:     background-color: #999999;

  11:     width: 80%;

  12: }

  13: #navigation {

  14:     margin: 5px 10px 25px 10px;

  15:     height: 40px;

  16:     background-color: #FFFFFF;

  17:     color: #000000;

  18: }

  19: #form {

  20:     margin: 10px;

  21:     padding: 15px;

  22:     background-color: #800000;

  23:     color: #FFFFFF;

  24: }

  25: .inputLabel {

  26:     width: 75px;

  27:     display: inline;

  28:     float: left;

  29: }

  30: body {

  31:     background-color: #999999;

  32: }

  33:  

  34: label, input{

  35:     margin:2px;

  36: }

  37:  

  38: label.error {

  39:     color: black;

  40:     font-weight: bold;

  41: }

  42: .addressField {

  43:     width: 175px;

  44: }

  45:  

  46: #txtAddress2

  47: {

  48:     margin-left: 81px;

  49: }

  50:  

  51: #leftColumn {

  52:     color: #FFFFFF;

  53:     background-color: #800000;

  54:     padding: 15px 15px 15px 15px;

  55:     margin: 0px 2px 5px 15px;

  56: }

  57: #centerColumn {

  58:     color: #800000;

  59:     background-color: #FFFFFF;

  60:  

  61:     padding: 15px 15px 15px 15px;

  62:     margin: 0px 2px 5px 2px;

  63: }

  64: #rightColumn {

  65:     color: #FFFFFF;

  66:     background-color: #800000;

  67:     padding: 15px 15px 15px 15px;

  68:     margin: 0px 5px 5px 2px;

  69: }

  70: .columns {

  71:     width: 32%;

  72:     height: 300px;

  73:     display:inline-block;

  74:     float:left;

  75: }

  76:  



Now that that's done.  The page renders something similar to the image below.


jquery1 - Scriptless


Nothing too glamorous.  The column/adjacent <div> tags at the bottom wrap to a second line but overall everything is as it should be. 


Now it's time to apply some of the UI elements of the jQuery framework.  First, let's go ahead and center the container tag.  I'm not a fan of the <center> tag so having a jQuery Plug-In to write handle the screen width and centering dynamically takes a lot of time off a task is pretty common.


To use the Center jQuery Plug-In, we first need to reference 3 JavaScript files; jquery-1.2.6.js, jquery.center.js, and our script TestScript.js.  For this example, I'm adding the script to the /Scripts/ directory.




   1: <script type="text/javascript" language="javascript" src="Scripts/jquery-1.2.6.js"></script>
   1:  
   2: <script type="text/javascript" language="javascript" src="Scripts/jquery.center.js">
   1: </script>
   2: <script type="text/javascript" language="javascript" src="Scripts/TestScript.js">
</script>



We have everything that we need to use the Center Plug-in.  The only thing we need to do is to write a little JavaScript in our file, TestScript.js.  Let's look at the code and I'll dissect next.




   1: $(document).ready(function(){

   2:     $("#container").center({

   3:         vertical: false    

   4:     });

   5: });



There's a number of things going on here but first, a quick jQuery syntax 101 lesson. 


The $ function is used to retrieve element(s) from the DOM and to interact with them through the returned jQuery JavaScript Object.  Also, the $ function's parameter uses CSS syntax to select the element or elements to manipulate. 


On line 2 we see $("#container").  This syntax retrieves the HTML element with the ID of "container".  So for line 1, $(document) selects the DOM/JavaScript document object.  Again though, this is a jQuery object and not the normal document object that we remember from document.getElementById(...).


Line 1 sets a new function to be called when the document is ready.  Inside that function, we are selecting the tag with the ID of "container".  Once we have the jQuery object for the container element, we are calling the center() function.  The center() function is an extension to the jQuery object that is provided by the Center jQuery Plug-in.  Line 3 is telling the center function to only center the container element horizontally.


Below is the now-centered UI.


jquery1 - centered


The last thing for this initial (and longer) entry will be to implement the rounded corners.  I'm not much of a graphics guy (though am learning Expressions Design) so having a simple and effective way to create cross browser compatible corners on the fly is appealing.  This really shows where jQuery's $ function is powerful. 


To implement the rounded corners code, we need to add the jquery.corners.js file to the HTML page.  After that, we just need to add to the code with in the $(document).ready(...) function in our JavaScript file.  Below is the updated function.




   1: $(document).ready(function(){

   2:  

   3:     $("#container").center({

   4:         vertical: false    

   5:     });

   6:     

   7:     $(".rounded").corners("20px");    

   8:     $(".columns").corners("top 20px");    

   9: });



We have only added lines 7 and 8.  We are first selecting all elements associated with the CSS classes rounded and columns.  Next we are calling the corners() function that also extends the jQuery object returned by the $ function.  This function will generate the rounded corners for us based on the parameters we pass it.  On Line 7, we are passing "20px" to say that we want the vertical and horizontal radii to be 20px each.  Line 8 does the same thing; however, we have signified we only want the top two corners to be rounded.


Below is the rounded UI.


jQuery1 - rounded


The rounding of the corners removed some of the line breaks and truly polished up the UI.  So, from 9 lines of JavaScript, we have took a very rough looking UI and converted it into a semi-professional looking template for us to build off of.


The next post on the series will a small bug that I discovered while playing around with this and how I managed to fix it. Afterwards we'll be looking at a simple post of showing and hiding the header (just for kicks).


Additional Resources:



  • jQuery's Web site - link

  • Center Plug-In documentation - link

  • Rounded Corners documentation - link


kick it on DotNetKicks.com