04 · 27

24 Irresistible jQuery Tips to Power Up Your JavaScript Skills

24 Irresistible jQuery Tips to Power Up Your JavaScript Skills

jQuery makes using JavaScript easy even for most designers because of it’s huge community and supply of really useful plugins. Using plugins is great for sure but knowing a bit more of what is going on behind the curtain can make you more powerful than you would expect. Digging into the coding details may not be that simple but with the good examples, tips and tricks in this article you should have a good chance.


Storing Data

Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes like fx.:

$('selector').attr('alt', 'data being stored');
// later the data can be retrieved using:
$('selector').attr('alt');


HTML attributes is not meant to store data like that and the "alt" as a parameter name does not really make sense. The right alternative in most cases is using the data method in jQuery. It allows you to associate data with an element on the page.

$('selector').data('paramtername', 'data being stored');
// then later getting the data with
$('selector').data('paramtername');


This approach allows you to store data with meaningful names and it is more flexible as you can store as much data as you want on any element on the page. For more information about data() and removeData(), see here jQuery internals One classical use of this is saving the default value of a input field because you want to clear it on focus.

<form id="testform">
 <input type="text" class="clear" value="Always cleared" />
 <input type="text" class="clear once" value="Cleared only once" />
 <input type="text" value="Normal text" />
</form>
 
$(function() {
 //Go through every input field with clear class using each function
 //(NB! "clear once" is two classes clear and once)
 $('#testform input.clear').each(function(){
   //use the data function to save the data
   $(this).data( "txt", $.trim($(this).val()) );
 }).focus(function(){
   // On focus test for default saved value and if not the same clear it
   if ( $.trim($(this).val()) === $(this).data("txt") ) {
     $(this).val("");
   }
 }).blur(function(){
   // Use blur event to reset default value in field that have class clear
   // but ignore if class once is present
   if ( $.trim($(this).val()) === "" && !$(this).hasClass("once") ) {
     //Restore saved data
     $(this).val( $(this).data("txt") );
   }
 });
});

Demo here

Columns of equal height

This tip show you how to use two CSS columns, and make them having exactly the same height?

function equalHeight(columns) {
    tallest = 0;
    columns.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    columns.height(tallest);
}

/*
How it works:
$(document).ready(function() {
    equalHeight($(".box"));
});
*/

Test and improve you jQuery selector skills

This jQuery selector Lab is really cool and can be used free online and you can even download the lab and use it off-line. There’s a test page with most of the combination of html fields you can imagine and then a very long list of predefined selectors you can try. If that is not enough you can also type in your own selectors. web-design-tutorial

Target blank links

Did you know that XHTML 1.0 Strict don’t allow “target=blank” attribute on links? Still it is quite useful to keep visitors on the site when they press an external link. A good solution to this problem should be using JQuery to make links opening in new windows. The rel=”external” attribute is used to match the links that we want to open in a new window.

$('a[@rel$='external']').click(function(){
  this.target = "_blank";
});

/*
This is how it works:
tripwiremagazine.com
*/

Test if a jQuery collection contains any elements

If you need to test if a jQuery collection contains any elements you can simply try accessing the first element like this:

if($(selector)[0]){...}
// or you may use
if($(selector).length){...}


Let look at an example:

//ex. if you have this html on a page
<ul id="shopping_cart_items">
  <li><input class="in_stock" name="item" type="radio" value="Item-X" />Item X</li>
  <li><input class="unknown" name="item" type="radio" value="Item-Y" />Item Y</li>
  <li><input class="in_stock" name="item" type="radio" value="Item-Z" />Item Z</li>
</ul>
 
<pre lang="javascript" escaped="true">...
//The condition in this if statement will evaluate to true because we have two
// input fields that match the selector and the <statement> will be executed
if($('#shopping_cart_items input.in_stock')[0]){<statement>}

Use Callback to synchronize Effects

If you want to ensure that events occur one after the other you should use callbacks. Functions allow us to register a callback once the operation is over like this: slideDown( speed, [callback] ) ie. $('#sliding').slideDown('slow', function(){... Try try the example below here.

<style>
 div.button    { background:#cfd; margin:3px; width:50px;
   text-align:center; float:left; cursor:pointer;
   border:2px outset black; font-weight:bolder; }
 #sliding      { display:none; }
</style>
<script>
 
$(document).ready(function(){
// Use jQuery to change look of div once clicked and the event to
//start off the slide effect
 $("div.button").click(function () {
   //div.button will now look like a pushed down button
   $(this).css({ borderStyle:"inset", cursor:"wait" });
   //The hidden #sliding will now slide down and use callback to start the
   //slideup once it completes
   $('#sliding').slideDown('slow', function(){
     $('#sliding').slideUp('slow', function(){
       //once the slide up is over the callback change css for button back
       $('div.button').css({ borderStyle:"outset", cursor:"auto" });
     });
   });
 });
});
</script>

Use Events to control DOM Elements and Custom Objects

One of the most useful parts of jQuery is it’s ability to attach events to objects within a web page. When these events are triggered you can then use a custom function to do pretty much whatever you want with the event.There is a wide range of Events that are supported by jQuery and you will be able to create your own as well. Binding events to page elements doesn't get much easier and elegant here a few examples.

//Bind click event to a paragraph and write click coordinates to the page
$("p").bind("click", function(e){
  var str = "( " + e.pageX + ", " + e.pageY + " )";
  $("span").text("Click at coordinates: " + str);
});
 
//Binding multiple events is also simple and
$("p").bind("mouseenter mouseleave", function(e){
  //toggleClass adds the specified class if it is not present, removes
  //the specified class if it is present.
  $(this).toggleClass("mouse-over");
});


Not only can you bind events to DOM elements as simple as just illustrated. With jQuery you can actually bind a custom event to ANY object. Here is an example.

}
function shoppingCart() {
  // Do general shopping cart stuff here...
};
 
var myShoppingCart = new shoppingCart('personalShoppingCart');
jQuery(myShoppingCart).bind('addItem', function() {
  // Custom event handling for adding items to the shopping cart...
});
 
// Trigger custom event:
jQuery(myShoppingCart).trigger('addItem');
);

Learn to use Custom Selectors

On top of standard CSS selectors jQuery allow you to define custom selectors that makes your code even more simple.

$.expr[':'].mycustomselector= function(element, index, meta, stack){
    // element- is a DOM element
    // index - the current loop index in stack
    // meta - meta data about your selector
    // stack - stack of all elements to loop
 
    // Return true to include current element
    // Return false to explude current element
};
 
// Custom Selector usage:
$('.someClasses:test').doSomething();


Lets take a look at an example. This custom selector will return elements in the scope specified with attribute "rel":

$.expr[':'].withRel = function(element){
  var $this = $(element);
  //simply returning elements where rel is not empty
  return ($this.attr('rel') != '');
};
 
$(document).ready(function(){
//Using the custom selector is simple and the collection returned support chaining
// as illustrated here to apply some css to the returned elements
 $('a:withRel').css('background-color', 'green');
});
...
<ul>
  <li>
    without rel
  </li>
  <li>
    with rel
  </li>
  <li>
    without rel
  </li>
  <li>
    a link with rel
  </li>
</ul>

Remove a word in a text

It is quite simple with jQuery to remove words in a element text? The following code can be easily modified to replace a word by another. In this case “wordtokill” is replaced by “wordtolive”.

var element= $('#id');

element.html(element.html().replace(/wordtokill/ig, "wordtolive"));

Make entire Elements click-able

A lot of menus are created using simple <li> lists and css. It would be nice for the website usability if navigation was provided for the entire <li> and not just for the link text. jQuery makes this possible in a pretty simple way by taking the href (url) from the embedded link.

<ul>
  <li>home</li>
  <li>about</li>
  <li>contact</li>
</ul>
...
//selector select all li within the ul and then we make them clickable.
$("ul li").click(function(){
  //get the url from href attribute and launch the url
  window.location=$(this).find("a").attr("href"); return false;
});

Preloading images

Generally it is a good idea to preload images if they are used in javescripts.

<pre>//Define function that preloads a defined list
//of images (arguments for the function).  
 
jQuery.preloadImages = function(){
  /Loop through the images
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
 
  }
}
// You can use usage the script this way:
$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png");

Disable right-click contextual menu

As with other things we have been doing for years using javascript jQuery makes it simpler and more elegant. Of cause you can use this for much more. You may do something when the contextmenu event is fired.

<pre><pre>$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
})

Make code simpler using group queries

A useful way to make the code simpler and easier to read is by grouping the queries for elements that need the same treatment.

// Don't do it like this as it takes up unnecessary space and takes time to write
$('div.close').click(doSomething);
$('button.close').click(doSomething);
$('input.close').click(doSomething);
 
// Simply use group queries in the selector if you have to
//apply same operation to them all
$('div.close, button.close, input.close')
    .click(doSomething);

Test your code well

jQuery comes with a unit test framework called QUnit. Writing tests is quite easy and allow you to confidently modify your code while ensuring that it still works as expected. Here is how it works:

<pre>//Separate tests into modules.
module("Module B");
 
test("some other test", function() {
  //Specify how many assertions are expected to run within a test.
  expect(2);
  //A comparison assertion, equivalent to JUnit's assertEquals.
  equals( true, false, "failing test" );
  equals( true, true, "passing test" );
});

web-design-tutorial

Minimize download time

Most browsers only download one script at the time and if you have several scripts being loaded on every page it can impact your download time. You can use Dean Edwards service "packer" to compress your scripts and make download faster. You need to maintain a development version and a runtime version as all you in-line comments will be lost. You will find it here.

jquery-tips

Another solution that take this to the extreme is interesting to take a look at. Basically it is a server based PHP script that combine javasctipt files and compress them in a easy to maintain approach. Take a look at and see if you can use the idea and some elements of the concept "Make your pages load faster by combining and compressing javascript and css files".

Logging to the Firebug console in jQuery

Firebug is one of my favourite Firefox extensions providing tons of tools in a very usable structure to aid you in HTML+CSS+JavaScript development. Obviously it is worth having just for it's excellent inspection feature allowing you to jump into the html and css and learn in a visual way what elements of the page is rendered by what code. As a jQuery and general Javascript developer Firefox also has good support for logging in your JavaScript code. The easiest way to write to the Firebug console looks like this:

console.log("hello world")

jquery-tips

You can pass as many arguments as you want and they will be joined together in a row, like

console.log(2,4,6,8,"foo",bar)


As a jQuery developer it even gets better using a tiny extension that Dominic Mitchell came up with to log any jQuery object to the console .

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};


With this extension you can simply call .log() on the object you are currently addressing fx.:

$('#some_div').find('li.source > input:checkbox')
    .log("sources to uncheck")
    .removeAttr("checked");

Use ID as Selector whenever possible

Selecting DOM elements using the class attribute is simpler than ever using jQuery. Even though it is simple it should be avoided whenever possible as as selecting using ID is much faster (In IE the class selector seams to loop through the entire DOM why generally it should be avoided). Selecting elements using IDs is fast because the browsers have the native getElementByID method that jQuery will use for IDs. Selecting classes still requires the DOM to be traversed behind the scene and if it is a large DOM and you make several lookups the performance impact can be significant. Let take a look at this simple html code:

<div id="main">
<form method="post" action="/">
  <h2>Selectors in jQuery</h2>
  ...
  ...
  <input class="button" id="main_button" type="submit" value="Submit" />
</form>
</div>
 
...
//Selecting the submit button using the class attribute
//like this is much slower than...
var main_button = $('#main .button');
 
//Selecting the submit button directly using the id like this
var main_button = $('#main_button');

Use Tags Before Classes

When you are selecting through tags jQuery will use the native browser JavaScript method, getElementsByTagName(). ID is still faster but this is still much faster than selecting with a class name.

<ul id="shopping_cart_items">
  <li><input class="in_stock" name="item" type="radio" value="Item-X" /> Item X</li>
  <li><input class="3-5_days" name="item" type="radio" value="Item-Y" /> Item Y</li>
  <li><input class="unknown" name="item" type="radio" value="Item-Z" /> Item Z</li>
</ul>


It is important to prefix a class with a tag name (here this is "input") and then it is important to descend from an ID to limit the scope of the selection:

var in_stock = $('#shopping_cart_items input.in_stock');

Cache jQuery Objects

Caching an object before working with it is essential for performance. You should neverdo like this:

<li>Description: <input type="text" name="description" value="" /></li>
...
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');
$('#shopping_cart_items input.text').css('background-color', 'red');
$('#shopping_cart_items input.text').val("text updated");


In stead cache the object and work on it. The example below should really use chaining but it is just for illustration.

var input_text = $('#shopping_cart_items input.text');
input_text.css('border', '3px dashed yellow');
input_text.css('background-color', 'red');
input_text.val("text updated");
 
//same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text
 .css('border', '3px dashed yellow')
 .css('background-color', 'red')
 .val("text updated");

Bind certain jQuery functions to $(window).load event

Most jQuery code examples and tutorials instruct us to bind our jQuery code to the $(document).ready event. In many cases this is OK but since $(document).ready occurs during page render while objects are still downloading it may cause problems for some types of scripts. Functionality such as binding visual effects and animations, drag and drop, pre-fetching hidden images etc. could benefit from being bound to the $(window).load as it will ensure that all dependant elements are ready for use.

$(window).loadspan<span style="
04 · 27

Contextual Slideout Tips With jQuery & CSS3

By now, you’ve probably heard about Adobe’s new CS5 software pack. Also, you’ve probably seen their product pages, where they present the new features of the suite. Apart from the great design, they’ve also implemented an interesting solution for showcasing the new features their products are capable of – using contextual slideout tips.

Knowing the importance of HTML standards, we are making a set of contextual slideout tips with jQuery & CSS3, which are ideal for product pages and online tours. As a bonus, they are SEO friendly, so all the content is visible to search engines.

The idea

The main idea is to create an easily configurable set of contextual slideouts. Each can be opened in one of four directions – bottom-right (default), bottom-left, top-left and top-right, and each can be in one of three colors – green (default), blue, and red.

To create a slideout element, you need to include a regular paragraph p tag to the page. This means that all the content is visible to search engines in a semantic way. The paragraphs are replaced with the markup for the slideouts by jQuery on page load, with the title, class and style attributes of the paragraph passed to the newly created element.

Contextual Slideouts

Contextual Slideouts

Step 1 – XHTML

Now lets take a look at the structure of the paragraph tags you should add to the page, and how they are configured.

demo.html

01<div class="main">
02 
03    <p title="A New Tutorial Every Week" style="top:200px;left:120px;">
04        This slideout is going to open to the bottom-right (the default).
05    </p>
06 
07    <p title="2200+ Twitter Followers" class="openTop openLeft blue" style="top:400px;left:650px;">
08        This slideout is going to open to the top-left.
09    </p>
10 
11    <p title="Over 5000 RSS Subscribers" class="openTop red" style="top:500px;left:90px;">
12        This slideout is going to open to the top-right.
13    </p>
14 
15</div>

As you can see, each of the tags contains a style, a class (optional) and a title attribute. As discussed above, these are copied to the slideouts when jQuery replaces the markup.

The style attribute contains the coordinates relative to the parent div element, which means that the slideouts are positioned in exactly the same place as the paragraphs.

The class attribute is optional and specifies a number of options for the slideouts. You can choose the direction to which the slideouts open, and their color.

slideout markup

01<div class="slideOutTip openLeft blue" style="left:100px;top:200px">
02 
03    <div class="tipVisible">
04        <div class="tipIcon"><div class="plusIcon"></div></div>
05        <p class="tipTitle">The title of the slideout</p>
06    </div>
07 
08    <div class="slideOutContent">
09        <p>Slideout Content</p>
10    </div>
11</div>
Structure of the Slideout

Structure of the Slideout

Step 2 – CSS

Now lets take a closer look at the styling. Only the styles directly used by the slideouts are presented here. You can see the rest of the styles in styles.css in the download archive.

styles.css – Part 1

01.slideOutTip{
02    /* The main wrapping div of the slideout tips */
03    position:absolute;
04    padding:3px;
05    top:0;
06    left:0;
07    background-color:#111;
08    font-size:13px;
09    color:white;
10    overflow:hidden;
11    height:22px;
12}
13 
14.slideOutTip:hover{
15    /* Applying a CSS3 outer glow on hover */
16    -moz-box-shadow:0 0 1px #999;
17    -webkit-box-shadow:0 0 1px #999;
18    box-shadow:0 0 1px #999;
19}
20 
21/* The holder for the title and the icon: */
22.tipVisible{ cursor:pointer; height:22px; }
23 
24.tipTitle{
25    float:left;
26    font-family:'Myriad Pro',Arial, Helvetica, sans-serif;
27    font-size:15px;
28    font-weight:bold;
29    white-space:nowrap;
30    line-height:22px;
31    padding-right:5px;
32}
33 
34.tipIcon{
35    width:20px;
36    height:20px;
37    float:left;
38    background-color:#61b035;
39    border:1px solid #70c244;
40    margin-right:8px;
41 
42    /* CSS3 Rounded corners */
43 
44    -moz-border-radius:1px;
45    -webkit-border-radius:1px;
46    border-radius:1px;
47}

The tipVisible contains the tipTitle and tipIcon divs, floated to the left inside it. These are the only divs that are visible to the user when the page loads. In the jQuery step of the tutorial, you will see that we are also binding an event listener for the click event on tipVisible, which slide-opens the content.

styles.css – Part 2

01/* Three color themes */
02.green .tipIcon{ background-color:#61b035; border:1px solid #70c244; }
03.blue .tipIcon{ background-color:#1078C7; border:1px solid #1e82cd; }
04.red .tipIcon{ background-color:#CD3A12; border:1px solid #da421a; }
05 
06.plusIcon{
07    /* The plus icon */
08    width:13px;
09    height:13px;
10    background:url('img/plus.gif') no-repeat center center;
11    margin:4px;
12 
13    /* Defining a CSS3 animation. Currently only works in Chrome and Safari */
14    -webkit-transition: -webkit-transform 0.2s linear;
15    -moz-transition: -moz-transform 0.2s linear;
16    transition: transform 0.2s linear;
17}
18 
19.slideOutTip.isOpened{ z-index:10000; }
20 
21.slideOutTip.isOpened .plusIcon{
22    /* Applying a CSS3 rotation  to the opened slideouts*/
23    -moz-transform:rotate(45deg);
24    -webkit-transform:rotate(45deg);
25    transform:rotate(45deg);
26}
27 
28/* Special rules for the left and top - opening versions */
29 
30.openLeft .tipIcon{
31    /* Floating the title and the icon to the right */
32    margin:0 0 0 8px;
33    float:right;
34}
35.openLeft .tipTitle{ float:right; padding:0 0 0 5px; }
36.openLeft .slideOutContent{ margin-top:22px; }
37.openLeft.openTop .slideOutContent{ margin-top:0; }
38 
39.slideOutContent{
40    /* Hiding the div with the slide out content: */
41    display:none;
42    padding:10px;
43    font-size:11px;
44}
45 
46/* Hiding the original paragraphs if they have not been replaced (JS disabled): */
47 
48.main > p{ display:none; }

The default version of the slideout opens to the bottom-right. You can change this by assigning the openLeft or openTop class to the original p you add to the page (remember that the classes of the p tags are copied to the structure of the slideout).  You can also change the color of the icon to blue or red by also assigning the respective class names.

A number of CSS3 rues are used here. Along the usual border-radius (for rounded corners) and box-shadow (for a outer-glow effect), I added the transform:rotate(45deg) property, which rotates the plus sign when the slideout is opened.

If you view the example in Safari/Chrome (or version 3.7 of Firefox, which is yet to be released), you can even see that the rotation is animated. This is done with the CSS3 transition property, inside which we specify the property that is going to be animated, the duration of the effect and the type of the animation.

Lastly, we use the .main > p to hide the p tags that are directly inside the main div, so if JavaScript is disabled, you will not see the paragraphs. You could alternatively style and incorporate them in your design for a proper fallback solution.

Closed Slideout

Closed Slideout

Step 3 – jQuery

When the page loads, jQuery loops through all the paragraph elements in the main div, and replaces them with the markup of the slideouts. It later binds event listeners for the click event and slides open the content in the direction that was specified with the class names when the event occurs. Lets see how this works.

script.js – Part 1

01$(document).ready(function(){
02    /* The code here is executed on page load */
03 
04    /* Replacing all the paragraphs */
05    $('.main p').replaceWith(function(){
06 
07        /*
08            The style, class and title attributes of the p
09            are copied to the slideout:
10        */
11 
12        return '\
13        <div class="slideOutTip '+$(this).attr('class')+'" style="'+$(this).attr('style')+'">\
14            \
15            <div class="tipVisible">\
16                <div class="tipIcon"><div class="plusIcon"></div></div>\
17                <p class="tipTitle">'+$(this).attr('title')+'</p>\
18            </div>\
19            \
20            <div class="slideOutContent">\
21                <p>'+$(this).html()+'</p>\
22            </div>\
23        </div>';
24    });
25 
26    $('.slideOutTip').each(function(){
27 
28        /*
29            Implicitly defining the width of the slideouts according to the
30            width of its title, because IE fails to calculate it on its own.
31        */
32 
33        $(this).width(40+$(this).find('.tipTitle').width());
34    });
35 
36    /* Listening for the click event: */
37 
38    $('.tipVisible').bind('click',function(){
39        var tip = $(this).parent();
40 
41        /* If a open/close animation is in progress, exit the function */
42        if(tip.is(':animated'))
43            return false;
44 
45        if(tip.find('.slideOutContent').css('display') == 'none')
46        {
47            tip.trigger('slideOut');
48        }
49        else tip.trigger('slideIn');
50 
51    });

As of version 1.4 of the jQuery library, the replaceWith() method can take a function as a parameter. This is really handy, as it allows us to dynamically generate the markup. The this points to the element, so we can easily get the values of the different attributes and the contents of the paragraph.

script.js – Part 2

01$('.slideOutTip').bind('slideOut',function(){
02 
03    var tip = $(this);
04    var slideOut = tip.find('.slideOutContent');
05 
06    /* Closing all currently open slideouts: */
07    $('.slideOutTip.isOpened').trigger('slideIn');
08 
09    /* Executed only the first time the slideout is clicked: */
10    if(!tip.data('dataIsSet'))
11    {
12        tip .data('origWidth',tip.width())
13            .data('origHeight',tip.height())
14            .data('dataIsSet',true);
15 
16        if(tip.hasClass('openTop'))
17        {
18            /*
19                If this slideout opens to the top, instead of the bottom,
20                calculate the distance to the bottom and fix the slideout to it.
21            */
22 
23            tip.css({
24                bottom  : tip.parent().height()-(tip.position().top+tip.outerHeight()),
25                top     : 'auto'
26            });
27 
28            /*
29                Fixing the title to the bottom of the slideout,
30                so it is not slid to the top on open:
31            */
32            tip.find('.tipVisible').css({position:'absolute',bottom:3});
33 
34            /*
35                Moving the content above the title, so it can
36                slide-open to the top:
37            */
38            tip.find('.slideOutContent').remove().prependTo(tip);
39        }
40 
41        if(tip.hasClass('openLeft'))
42        {
43            /*
44                If this slideout opens to the left, fix it to the right so
45                the left edge can expand without moving the entire div:
46            */
47            tip.css({
48                right   : Math.abs(tip.parent().outerWidth()-(tip.position().left+tip.outerWidth())),
49                left    : 'auto'
50            });
51 
52            tip.find('.tipVisible').css({position:'absolute',right:3});
53        }
54    }
55 
56    /* Resize the slideout to fit the content, which is then faded into view: */
57 
58    tip.addClass('isOpened').animate({
59        width   : Math.max(slideOut.outerWidth(),tip.data('origWidth')),
60        height  : slideOut.outerHeight()+tip.data('origHeight')
61    },function(){
62        slideOut.fadeIn();
63    });

We are binding two custom events to the slideout – “slideIn” and “sldieOut“. This way it is easier to initiate the opening and closing by just triggering the respective event.

Depending on whether one of the ‘openLeft‘ or ‘openRight‘ classes are assigned to the slideout, we apply some additional rules to the elements, so that they can slide-open properly.

After this we assign the isOpened class to the slideout. Not only it marks the slideout as opened, it also applies a z-index of 10000 so it shows on top of all the other elements on the page.

script.js – Part 3

01    }).bind('slideIn',function(){ // Binding the slideIn event to .slideOutTip
02        var tip = $(this);
03 
04        /* Hide the content and restore the original size of the slideout: */
05 
06        tip.find('.slideOutContent').fadeOut('fast',function(){
07            tip.animate({
08                width   : tip.data('origWidth'),
09                height  : tip.data('origHeight')
10            },function(){
11                tip.removeClass('isOpened');
12            });
13        });
14 
15    });
16 
17}); /* Closing $(document).ready() */

The closing of the slideout consists of running an animation which returns the element to its original size (saved with the data() method) and removing the isOpened class.

With this our contextual slideouts are complete!

Conclusion

The slideouts are ideal for presenting only the highlights of a product, with the details neatly hidden away. You can easily incorporate images, videos, or any other rich multimedia content, to create a unique experience for your visitors.

04 · 27

How To Debug PHP Code And Useful PHP Debugging Tools

PHP does not have an internal debugging facility. You can use only external tools to debug PHP code. Here i tried to list down PHP debugging tools, which are extremely useful, but listing down these tools was not enough because you don’t know how to use them so i have compiled those tutorials too.

Here is the list of tools:

PHP Debugging Tools

1. Gubed PHP Debugger

Gubed is a cross platform program to debug PHP scripts.

Gubed PHP Debugger

2. PHP Debug

The basic purpose of PHP_Debug is to provide assistance in debugging PHP code, by “debug” i don’t mean “step by step debug” but program trace, variables display, process time, included files, queries executed, watch variables.

PHP Debug

3. DBG

DBG is a a full-featured php debugger, an interactive tool that helps you debugging php scripts.

DBG | PHP Debugger and Profiler

4. PHP Dyn

PHP Dyn is PHP Extension to help debugging a PHP script.You can get execution trace of scripts not to need change them.HTTP request parameter can be printed.Argument value of the function call and return value can be printed.

PHP Dyn

5. Xdebug

The Xdebug extension helps you debugging your script by providing a lot of valuable debug information.

Xdebug extension

5. Webgrind

Webgrind is an Xdebug profiling web frontend in PHP5. It implements a subset of the features of kcachegrind and installs in seconds and works on all platforms.

Webgrind PHP Debugger

6. MacGDBp

Debugging a live, running PHP application has never been so easy. It’s a live PHP debugger application for the Mac OS.

MacGDBp PHP Debugger

7. Advanced PHP Debugger

APD is a full-featured profiler/debugger that is loaded as a zend_extension. It aims to be an analog of C’s gprof or Perl’s Devel::DProf.

Advanced PHP Debugger

How To Debug PHP Code

How to Debug PHP Using Firefox with FirePHP

This article shares an elegant, simple, and more maintainable way of debugging Ajax apps via the web browser (more specifically for the Mozilla Firefox browser). You’ll learn the basics of leveraging Firefox in conjunction with Firebug and FirePHP to implement FirePHP libraries on web apps and logging messages in the Firebug console.

Debug PHP Using Firefox with FirePHP

How to Debug in PHP

This article breaks down the fundamentals of debugging in PHP, helps you understand PHP’s error messages and introduces you to some useful tools to help make the process a little less painful.

How to Debug in PHP

Debugging PHP using Eclipse and PDT

Use XDebug or Zend Debugger to boost your productivity when fixing bugs in PHP applications.

Debugging PHP using Eclipse

Debugging PHP with Xdebug

The Xdebug is the extension for PHP that helps debugging PHP scripts by providing a lot of valuable debug information. The debug information includes stack traces and function traces in error messages, memory allocation and protection for infinite recursions.

Debugging PHP With Xdebug

Debug PHP with DBG Wizard

You can easily debug PHP with PhpED’s PHP Debugger. Setting up your system to debug php scripts can be tricky but PhpED’s Settings Wizard can take care of the majority of the debugging configurations.

Debug PHP with DBG Wizard

04 · 27

Usability Do’s And Don’ts For Interactive Design

We often talk about how to make our websites more usable, whether it’s tweaking the HTML structure of pages to benefit the user’s process or figuring out how best to display a message via CSS. But we never bring this thought process into our jQuery-based (and other JavaScript-based) elements. How can we enhance the user experience and usability of our jQuery events?

Below, we’ll briefly discuss ways to look at the code and the result of our interactive designs and, thus, improve their usability.

[By the way: The network tab (on the top of the page) is updated several times a day. It features selected articles from the best web design blogs!]

Don’t Leave Users In The Dark

Most if not all jQuery is fired through events from the user, whether it’s loading new content, posting forms or simply modifying the presentation of an item. Such events are fired through a click from the user.

While as designers and developers we would know that something is happening, without a visual representation, the user is left guessing what is going on. If the user clicks an element and nothing occurs immediately, they could wonder whether the page is broken or they have done something wrong.

But by simply displaying a message or loading graphic for the user, they are assured that something is happening and that their action will be completed shortly.

Pinchzoom offers a consistent experience when loading new content by displaying a spinning graphic alongside the word “Loading.” The constant motion of the graphic tells the user that the website is working on their request.

Pinchzoom-loading in Usability Dos And Donts For Interactive Design


Pinchzoom shows a rotating graphic and text in a modal box to catch the user’s attention and tell them that content is loading.

Always Put Your Code To The Test

As part of any testing process, designers make sure that their interactive design will work across multiple browsers. Unfortunately, we do not test our design elements by using them as a normal user would. You’d be surprised how differently we use our own websites.

Users vary widely in their behavior and viewing set-ups, so don’t be reluctant to use your design in different ways and with different set-ups.

By trying to break your JavaScript, you could come across bugs that you didn’t notice before, which will lead you to create a stabler and more solid user experience. Coming across an element that appears to be broken or not functioning correctly will often make users lose trust in the website as a whole.

Don’t Add jQuery At The User’s Expense

One of the last things you want is a confused user. Adding too many interactive elements can make the user unable to decide what to do or how to find what they need.

When building your website, restrict the number of controls to those that will help the user achieve their goal. By restricting choice, you create a much more effective user experience.

An example of this problem can be seen on the Crispin Porter + Bogusky website. This website has a lot of scrolling navigation and many “Read more” links that load more content on the page. This overloads the user with information. New users might be unsure what to do, where to go or if they’ve missed important information.

Crispinporter-overloading-information in Usability Dos And Donts For Interactive Design


Crispin Porter + Bogusky shows too many options at once.

Speed Isn’t Always Key

We always optimize our code to load pages faster and help users complete their tasks more quickly. On the other hand, there are instances when slowing down animations could improve the usability of a website.

Animations such as those showing rotation through messages or pictures are often set too fast. We must remember that users don’t want to be rushed. Give them time to take everything in. A user shouldn’t be halfway through reading an item and then have to wait for it to rotate before being able to finish.

Whether you use a plug-in to generate the effect or core jQuery code, settings should be available to change the speed of the animation. In most cases, keywords such as “slow” or “fast” can be used. If you wish to be more exact with your timings, numeric values such as “800” or “1200” are available, which would specify time in milliseconds.

The home page of Postbox features a rotating list of news and key items. Though not a prominent feature of the design, the delay between each item is long enough to allow the user to fully absorb the information.

Postbox-rotating-messages in Usability Dos And Donts For Interactive Design


Rotating messages on the Postbox home page.

Make Tabs More Prominent

Though more of usability tip for design, this deserves mention nonetheless. If you are using tabs to show and hide content, make sure they are prominent and that each tab describes its content well.

Tabs are a great space-saver and some say they allow for more creativity in a design. But don’t risk the user overlooking potentially important content.

By making tabs prominent, you enable users to find more information easily should they need it. Also, being more descriptive in your labeling makes clear to the user what they should expect to see.

Delibar styles its tabs as bookmarks. The bold green draws the user’s attention. Delibar uses one-word labels to succinctly convey the product features and content behind the tabs. For example, the “Manage” tab leads to content that describes the numerous ways that users can manage their Delicious bookmarks using Delibar.

Delibar-tabs in Usability Dos And Donts For Interactive Design


Prominent tabs draw attention so that users do not miss important information.

Don’t Take Control Away From Users

One-page websites with smooth scrolling (horizontal and/or vertical) are a growing trend now. But don’t leave users stuck should they not want to use the navigation you provide.

Users who realize that the page extends beyond the fold will likely try to use their mouse or scroll bar to navigate down. Removing scrolling just shows how taking away basic browsing functionality (and thus taking control away from the user) can impair the overall experience. Users will feel that they are not in control of their own browsing.

If you are including page scrolling in your design, you could improve usability by providing keyboard navigation and shortcuts. This provide another option by which users can navigate the page. Now they’ll have the scroll bar, the mouse and the keyboard. jQuery for Designers has a tutorial on adding keyboard navigation using jQuery.

When deciding how your design and its jQuery should function, think of how your choices might impede basic functionality and how users might react to that.

While providing links to navigate down the page, designinsocial does not let users browse freely with their mouse or scroll bar. As you can see below, content exists below the fold and users will want to scroll down.

Designinsocial-control in Usability Dos And Donts For Interactive Design


Screenshot of designinsocial at 1024 x 768 pixel resolution.

Use jQuery To Improve Form Validation

jQuery can easily improve form validation and can be triggered either by the “Submit” button or by the user focusing off a field (.blur()). But remember that JavaScript form validation should never entirely replace server-side validation.

Using jQuery to help validate forms can have two very important benefits to users:

  1. The user won’t have to wait for the page to reload to learn that they made an error. Also, if the page has to reload before an error message is displayed, the user might assume that their submission was successful and overlook the message.
  2. jQuery allows for easier and more effective error highlighting; for example, by changing the border and background color of relevant inputs or by using animation, such as a tooltip, to catch the user’s attention.

Trevor Davis has an informative article entitled “AJAX Forms with jQuery,” which has some great tips on implementing form validation with jQuery.

Blueskyresumes-formvalidation in Usability Dos And Donts For Interactive Design


jQuery form validation for comments on Blue Sky Resumes.

Blue Sky Resumes uses jQuery on its blog comment form by changing the background and border color to highlight input fields with errors. A validation summary also appears above the form to further explain the error.

Prevent Animations From Stacking

One of the great features of jQuery is that it allows you to enhance a design by animating elements. This includes fading, changing colors and moving elements. One jQuery animation, often used to de-clutter an interface, is to hide information such as image captions and then display it on hover.

Cssbake-animation in Usability Dos And Donts For Interactive Design


A CSS showcase uses jQuery animation to display an item’s title and rating when you roll over the screenshot.

One problem that many designers and developers overlook, though, is that such animations can quickly “stack.” When a page has many thumbnails, and a user quickly hovers over several at a time, then the animation will drag behind one by one, even though the user has stopped moving their mouse. Hovering over the four panels on druckbar demonstrates this problem.

You can use one of two solutions to save users from this hassle. The first is the .stop() function. When .stop() is called on an element, the currently running animation (if there is one) is immediately stopped. For instance, for an element hidden with .slideUp(), when .stop() is called, the element will be displayed but at a fraction of its previous height. Callback functions are not called.

CSSbake uses the following function in the example shown above to prevent animations from stacking:

1$("ol#gallery li").hover(function () {
2$(".thumb-meta", this).stop().animate({ bottom: '0px' }, 400);
3},
4function () {
5$(".thumb-meta", this).stop().animate({ bottom: '-22px' }, 400);
6});

Alternatively, you could use a jQuery plug-in such as hoverIntent, which fires an animation only if the user’s mouse slows down enough, making it obvious that they are intentionally hovering over an element.

Keep Content Animation To A Minimum

Because JavaScript functions are so easy to implement with jQuery, many of us easily get carried away with animations, causing disruption for the user. Some websites use jQuery to load images as the user scrolls down the page, thus making the initial page load faster and allowing users to access content more quickly. Mashable, a popular social media news website, does this. While this is great for users who have a slow Internet connection, it does have its drawbacks.

The fade-in animation tied into this technique can be quite distracting for the user. If a user is steeped in an article, the fade-in as they scroll down might break their flow. It would be more effective if the image loaded with no animation, ideally just before the image area came into the viewport, to avoid disruption.

So, think about how animation and other jQuery functionality will affect the user’s ability to concentrate on the main content.

Conclusion

jQuery’s ever-growing popularity has brought to light the wide range of possibilities it offers. The points discussed here are just a handful of the current trends in interactive design. As you would with any design element, think of how your decisions will affect users. Is the element easy to use? Are the processes easily understandable? If something goes wrong for the user, how might they react? Questions like these can help iron out errors, giving users a more solid interactive design and user experience.

Showcase Of Websites With Effective jQuery

Crush + Lovely
Crush + Lovely uses jQuery to create a smooth scrolling effect when a navigation item is clicked. The user experience is enhanced through keyboard navigation: the left and right arrow keys scroll the page between sections.

Crushlovely-navigation in Usability Dos And Donts For Interactive Design

Shaun Inman
Shaun Inman uses jQuery to highlight the item that the user is hovering over. The other animations make the interface and experience more fun for the user.

Shauninman-navigation in Usability Dos And Donts For Interactive Design

Robotcat
Robotcat reinforces its newsletter sign-up form validation with jQuery, by highlighting any errors. Form fields are highlighted with a prominent red border.

Robocat-form-validation in Usability Dos And Donts For Interactive Design

Panelfly
Panelfly features tabbed content in its high-impact design so that the user does not miss important content.

Panelfly-tabs in Usability Dos And Donts For Interactive Design

Orman Clark
Orman Clark’s portfolio has fixed navigation and jQuery that create smooth scrolling between the sections of the one-page design, while still allowing the user to move with the scroll bar or mouse.

Ormanclark-navigation in Usability Dos And Donts For Interactive Design

Jan-Eike Koormann
Jan-Eike Koormann uses jQuery and AJAX to load items in his portfolio. When an item is loading, a graphic lets the user know that something is happening.

Janeikekoormann-loading in Usability Dos And Donts For Interactive Design

YAY Paul
YAY Paul uses hover events to animate and display the titles of his portfolio pieces. Using the methods described above, Paul West prevents animations from stacking.

Yaypaul-hoverevents in Usability Dos And Donts For Interactive Design

IconDock
IconDock uses jQuery to create a unique and playful experience when the user adds items to the cart. In addition to being able to click the “Add to Cart” links, users can drag icon images to the cart. A loading graphic lets users know that the cart is being updated.

Icondock-cart in Usability Dos And Donts For Interactive Design

Useful Resources

(al)

04 · 27

Google LatLong: Earth view comes to Google Maps

Kyle Reddoch

I am an aspiring Web Developer, Android Fanatic, Family Man, and all around Web Geek! I also do Freelance Development work.

About

My Journey through the Interwebs!