Copter Labs Copter Labs

Smart Design.

For Smart People.

Use jQuery to Enhance User Experience

User experience (commonly called UX) can be (and should be) fun. Helping someone engage with your site will keep them on your site for longer! jQuery gives us all the tools we need to do this very easily.

Simple things can be done to ehance elements that users need to mouse over or interact with, such as tables or links, which makes these elements easier and more intuitive to use.

Let's have a look at an example table; if you have a simple table with any amount of data in it, it can instantly look as boring as hell. To make the data more visually interesting (and, consequently, easier to read), how about highlighting the row that the user is in, enabling them to see all the data relavant in that row?

Name Surname Hometown
Garry McDuff GarryTown
Barry McDeff GarryTown
Harry McDuff GarryTown
Bob McFuff GarryTown
Carry McCuff GarryTown

This is extremely simple to do with jQuery — lets see the code:

// Tells the jQuery to start when the page loads - it's called the document ready function.
$(function() {

    // Target the element we want - and listen for the hover action by the user
    $('table td').hover(function() {

        //Target current td and add a background colour of yellow
        $(this)
            .css('background','yellow')

             // Find the parent of this cell and give it a red background
            .parent()
                .css('background','red');

    },

    // The hover function has a callback for when the mouse leaves the element too!
    function() {

        // We need to remove the style from the td with removeAttr()
        $(this)
            .removeAttr('style')

            // Now remove the background colour from the parent element
            .parent()
                .removeAttr('style');

    });

});

So as you can see in the commented breakdown:

First, make sure the document is ready. This starts the script when the elements have fully loaded, which ensures they are affected by the script

Next, target the element. You can do this by the actual element name or by its class or ID, using the same syntax as CSS (if our table had an ID of "UserDet" we could select it using $('#UserDet td').

Now we can get down to the real changes. First we have to target what we want to change when something is hovered over. jQuery has a parent() function that will target the parent of any element — in the table data's case, this is the table row element it is inside.

Once we have specified that the table row is what we want to change, we can then add some CSS magic. There are other better ways to add CSS to elements with jQuery, including adding actual classes that you can pre-define (links at the bottom of this post), but for this example we will keep it simple and use the css() function.

As you can see, to use the css() function you just input what we want to change, as a string. In this example we changed the background to red.

We can pass a small array through if we want to change more than one style item, but if you are looking to change more than one I would recommend setting up a class and then using addClass() instead of css(), because anything passed in via css() is styled inline, which is generally considered bad practice.

Now we come to the callback, which is triggered when the user moves out of the hover area. When they move out, we obviously want to remove the style. As the style is inline because of the way we added it with css(), we can just remove the style attribute using removeAttr('style')

If you went for the addClass('class') option, you can remove the class with (yup, you guessed it) removeClass('class'). Rocket science, eh?

Chaining is one of the greatest features of jQuery; it is basically means, well, "chaining" the functions one after another. Just make sure you have it in the right order. Above you can see we selected the table td and changed the css on that item first, then we continued the chain to the parent. If you select the parent first, then all changes afterwards happen on the parent level, unless you bring it back down again using end(). The moral is to order your actions in such a way that as little DOM traversal as possible is necessary.

Function Reference

Date. 01/29/2011

Comments. 4

Category. jQuery

Rob MacKay

Rob MacKay

Rob MacKay was born and bred in the Northwest of England, or as all English people know it "God's Country". His interest in new technology led him to become part of the gaming generation, with help from his brand spanking new Commodore 64 (and his parents' cash flow). Although gaming was the main pastime, he didn't stop there — his C64 also gave him the opportunity to create BASIC programs, which he used to create text-based adventure games, of course!

Was This Post Helpful? Pass It On!

Share the Love

If this post taught you something, reminded you of something you had forgotten, or just made you feel good, there's really no better way to say "thank you" than passing it along to your friends.

Don't forget to like us on Facebook, join our newsletter, and/or subscribe to our RSS feed to make sure you hear about new posts first!

Join Our Gaggle of Geeks
* indicates required

Comments.

  1. Gravatar

    I prefer to use toggle() function inside the hover() function like this

    $("table td").hover(function(){

    $(this).toggle(function(){

    $(this).css('background','yellow')

    }).parent().toggle(function(){

    $(this).css('background','red');

    });

    });

  2. Gravatar

    Hey :) Thx for the comment - you are very right too, great idea :)

  3. Gravatar

    Thanks for the quick jQuery overview.

    Some off-topic ;) Does this site based on custom CMS and written in pure php/html/css/js ?

  4. Gravatar

    Hey Nick - Yes we use a custom CMS written in PHP :)

    It is our default "goto" system that we use for our clients sites, although we do work in Wordpress too (well I do hehe)

Join In.

Have something to say? By all means, speak up!

But first, a few rules:

  • Don’t be a jerk.
  • Use your real name, not your business name - this is a discussion, not a billboard.
  • Only <strong>, <em>, and <code> are allowed tags.
  • Wrap code samples in <code> tags.

Happy commenting!

Add a Comment