Login
Home
Eoin Bailey . com
Tech, Research, Code, Work, and Fun
  • Home
  • Eoin's CV
  • About Eoin
  • Ph.D.
  • Blog
  • Galleries
  • Training
  • Polls
  • Tags
  • Weblinks
  • Site map
  • Contact

Tag Cloud

algorithm antarctica apple banking browser code copyright cycle data centre devel Dijkstra drupal drupalcamp economics escapades facebook firefox galway Google iphone ipod livigno theme training weights
more tags

A Random Image

PhysioCare

jQuery - Selectors - Plugins | Drupal

Submitted by Eoin on Sun, 12/07/2009 - 15:38
in
  • Code-Work
  • drupal
  • jquery
  • jquery selectors

I was doing some JavaScript coding, more specifically I was doing it in jQuery. I was having a little trouble with the selectors in jQuery, as such, this is my take on it, mixed with some infomation on jQuery plugins, and getting jQuery and jQuery UI to work in a Drupal theme.

Note: You have to add the JavaScript files for jQuery, jQuery plugins, jQuery UI if you want to use them on a page. I will focus on how to do this for a Drupal theme, but in general the following line needs to be added to the head of the page that you want to use jQuery on:

<!-- Change the value of 'src' to the location of your copy of jquery.js -->
<script type="text/javascript" src="jquery.js"></script>

jQuery

What is jQuery? I think this question is best answered by the jQuery guys themselves:


"jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development."

Basically jQuery abstracts away some of the arcane and confusing parts of JavaScript, making it quicker and easier to perform some common functions used on websites.

An example of what jQuery looks like:


// Sample jQuery

    $("p").fadeOut("fast").fadeIn(4000);

// END OF FILE

The above code will apply two effecs, in the order they are added to all paragraph elements on a page, i.e. everything contained within a <p> and </p> tag.

The effects applied are a 'fadeOut', with the argument 'fast'. This is fairly self explantory, the contents of the paragraph tags will be faded out from the page quickly, and then the 'fadeIn' effect is applied, and this fades the paragraph content back to a visibly state over 4000 milliseconds.

There are lots of effects built into the jQuery core, your best bet is to check them out on the jQuery site:

jQuery Effects

Plugins

jQuery plugins enable extra functionality within jQuery. A plugin is basically a new function, and once properly written, it can be accessed and used in exactly the same manner as any of the core jQuery effects or methods.

Similar to adding jQuery to a page that you want to use it on, as mentioned at the start of this post, you will have to add the file that contains the plugin to the page too, if you are going to use it, e.g.


<script type="text/javascript" src="javascript/jquery.plugin.js"></script>

jQuery UI

jQuery UI is effectively a plugin that has become so large and usfeul it is its own package now. It depends on jQuery core, so you will need that too, but jQuery UI also lets you do some funky stuff in your UI in a really clean simple manner.

e.g. an accordion:


$(function() {
    $("#accordion").accordion();
});

(Despite the fact I'm writing this up, I haven't added jQuery to this blog, I use it on other sites though - that's why there's no demonstration of the effect here, but it can be seen here: demo.)

If you are using jQuery on a production site, you will quite probably end up using jQuery UI.

jQuery Selectors

Now, onto the meat of this article: jQuery selectors. jQuery is powerful because it simplifies adding a number of pretty effects on your site. But you have to choose the correct element to apply the effect, i.e. you need to use the correct selector. This can become tricky. Once you can choose the correct element, it's a trivial task to apply effects, so, how do you select the correct element?

Constructing a Selector

What does a selector look like...


// An empty jQuery selector

$()


// Select every element on a page

$(*)


// Select all paragraph elements 

$("p")

The selector is a simple construct, to be honest, if the above code confuses you, it's time to hire a developer (shameless plug, I am one, contact me).

Standard Element Selectors

First of all, it's very easy to apply an effect to every element on a particular type or class. To select a particular element, just place that element name inside the selector construct:


// Select all 'p' elements:

$("p")


// select all div elements

$("div")


// select all 'a' (links/anchors) elements

$("a")

Class Selectors

To select all elements with a specific class, the selector becomes:


$(".class-name")


// change the colour of the background for all elements with class name "Orangutan"

$(".Orangutan").css({
    "background" : "orange"
});

id selectors

Selecting an element with a specific id is similar to selecting elemtns with a specific class:


$("#id-name")


// add the class "poop" to the element with id "brown"

$("#brown").addClass("poop");

Compound Selectors

This is where we start to add selectors together. This allows us to pick out a specific set of elements, e.g. pick the last column in a table in the following HTML:


<div id="table-container">
    <table>
        <tr>
            <td>
                First Column
            </td>        
            <td>
                Second Column
            </td>
            <td>
                Third Column
            </td>        
            <td>
                Fourth (last) Column
            </td>        
        </tr>
        <tr>
            <td>
                First Column
            </td>        
            <td>
                Second Column
            </td>
            <td>
                Third Column
            </td>        
            <td>
                Fourth (last) Column
            </td>        
        </tr>
    </table>   
</div>


// select the last column in the table above
// and add the class "last"

$("#table-container tr td:last").addClass("last");

This selector shows how to construct a compund selector. In this we start with the id 'table-container', we have now limited our selection to only elements found within this div. Next we select all table rows, or 'tr' elements, and finally within each row, the last item with 'td:last'.

This selector makes use of the 'last' capability, which finds the last in the list of the selected set of elements.

REALLY compound selectors

Things start to get interesting when you have duplicates of items, and you only want to apply an effect to a single element. For example, you have three boxes, each containing several more nested elements. Each of these boxes have identical structure and identical class and element names, e.g.:


// Each container is identical to below

<div class="box-container">
    <div class="top-left">
        <div class="top-right">
            <div class="bottom-right">
                <div class="bottom-left">
                    <div class="content">
                        <h2>A heading</h2>
                        <p>
                            Content, lots of content
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

The above code is replicated several times on the page. What you want to do is apply an effect to only the element (and the sub-elements) that the user has their mouse hovering over, initially we might try something like:


$(".box-container").hover(function() {
    $(".box-container top-left").addClass("selected-top-left");
    $(".box-container top-right").addClass("selected-top-right");
    ...
    ...
}
);

But, in doing that we will change the elements that are contained within ALL the boxes on the page, not just the one the user is hovering over.

Instead, we need to do something else...


$(".box-container").hover(function() {
    $(this).children("top-left").addClass("selected-top-left");
    $(this).children("top-left").addClass("selected-top-left");
    ...
    ...
    
}
);

The use of $(this) within the function, limits the elements to the set contained within only the current selection. That means the effects are applied to only the matches within the element the user is currently hovering over.

(If the html/css was better constructed, it would also be possible to make a change to every child element at once, such as move an image a certain amount on a hover event, however writing this in the most effecient manner possible is not the point of this little tutorial.)

Applying an Effect

The code below, makes use of all the parts of jQuery discussed so far. While the code looks relativley complicated, once broken down it is very easy to follow, and it quickly becomes intuitive.


// fade out all paragraphs, and then fade them back in

$("p").fadeOut("slow").fadeIn("fast");


/*
when a user hovers over the element with id "container-name", the first function is called (animating a change in the background over 5 seconds), when the moves the mouse off the container, the second function is called, which hides the element.
*/ 

$("#container-name").hover(function() {
        $(this).children("table").animate({
            backgroundColor : "red"
        }, 5000);
    }, 
    function() {
        $(this).hide();
    }
);

Enjoy!

Add a JavaScript File to a Drupal Theme

Finally, for all the Drupal themers out there, to add a javascript file to your theme (assuming you already have the file in your themes folder), open up the themes 'template.php' file, and add the following line, replacing &ltyour-theme-name&gt with the name of your theme:


drupal_add_js(drupal_get_path('theme', '<your-theme-name>') . '<path-to-javascript-filename-in-theme-directory>/jquery.js', 'theme');

  • Eoin's blog
  • Printer-friendly version
  • Send to friend

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

selectors

Submitted by DM (not verified) on Wed, 05/08/2009 - 17:58.

You seem to have missed this very important point about JQuery selectors:

They are a superset of CSS3 selectors, so any selector you can use in CSS to apply styles, you can use in JQuery to do *something* to an element.

  • reply

I see your point

Submitted by Eoin on Wed, 12/08/2009 - 14:46.

I see what you're saying. I don't think I *missed* it exactly, I just didn't mention that point explicitly. I wanted to keep clear of as many abbreviations as possible!

  • reply

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.

More information about formatting options

Current Poll

What is your current phone OS?:

Freelance Work

A sample of websites I have developed:

  • Studio Richards
  • Medilex
  • Design21C
  • The Spine Clinic
  • Abrivia - Careers and Outplacement
  • Emilie Conway

Twitter

Follow @eoinbailey

Some Links

  • James Bond Opening Scenes
  • Polls
  • Chess Module-Drupal
  • Ski Trip Jan 2009

Training

  • Spinning
  • Hodson Bay Hotel Training
  • Spinning Class - Not too Shabby!
  • Bike Time Trial
  • Spinning Class of Anti-Doom!

Recent Comments

  • Happy New Year 2012!
  • Thank you..
  • Simple way
  • Yep, CSS is an option - there
  • Maybe CSS is an easy solution?
  • Thanks for the direction.
  • Thank you for the insight.
  • Exactly.
  • Thank you for the insight.
  • I'm open to correction on

Powered by

Powered by Drupal, an open source content management system

Recent blog posts

  • Leap Card
  • A new College term - Dijkstra's Algorithm
  • Dublin GTUG - June 2011 - Over 100 attendees
  • City of a Thousand Welcomes
  • Groupon et al. - "Bet on the Future"
  • Dublin Web Summit - DWS6 - Roundup
  • Anti-Spam - Using a Catch-All to identify bad companies
  • Hide a Note Title - Drupal 7
  • The Election on Hit The Road
  • Syntax Highlighter Module - Javascript Problem
more
Copyright © 2012 Eoin Bailey . com.

I'm trying out: Web Analytics