Search

It’s all about CSS

Posted on 6th December 2007 — If you’ve got a good understand of CSS selectors, then you’re already familiar with how to query the DOM.

CSS1

jQuery uses CSS1, 2 and parts of CSS3 at the heart of all it’s queries, just in the same way you would use CSS to target an element or group of elements to style.

In CSS, to hide an element we could use:

.hidden { display: none; }

Using jQuery we can achieve the same effect by finding all the elements whose class is hidden and hiding them like this:

$('.hidden').hide();

Equally to target an ID, in CSS we use:

#header { display: none; }

Which is this in jQuery:

$('#header').hide();

CSS2

More complicated CSS selectors can be used using CSS2. Here we are styling all links that have an attribute of type="application/pdf" with a nice little icon, and doing something cool when they click on the link.

a[type="application/pdf"] { 
  background-image: url(/images/pdf.gif);
  padding-left: 20px;
}
$('a[type="application/pdf"]').click(doSomethingCool);

CSS3

Taking the above example further with CSS3 is easy. Let’s assume the markup already exists, and we want to find all the anchors that link to pdfs:

a[href$=".pdf"] { 
  background-image: url(/images/pdf.gif);
  padding-left: 20px;
}
$('a[href$=".pdf"]').click(doSomethingCool);

You should check the full jQuery selector documentation for which CSS3 selectors are supported.

If your page has a lot of markup, try to use context to narrow down the selector searching. Particularly, i.e. $('.hidden') can be slow if you have a 1,000 elements on the page.

Example

So you’ve got your built web page, fully styled and there’s no interaction layered on yet. Using these CSS selectors we can target elements and hook actions.

In this simple example we have a registration form. We have terms and conditions that if the user wants to read, they’ll slide out to be shown.

The terms are both linked to and hidden on the page. If the user clicks on the link and JavaScript is enabled, we’ll handle the click action ourselves by sliding the text in to view.

$(document).ready(function () { // when the DOM is ready do:
    $('A.reveal').click(function () {
        $('#terms').slideDown();
        return false; // don't follow the default link action
    });
});

This code breaks down as follows:

$(document).ready(function () {

Run the JavaScript in this (anonymous) function when the document has loaded.

$('A.reveal').click(function () {

Find all the anchors with the class ‘reveal’ and hook a click event.

$('#terms').slideDown();

When the user clicks, find the element whose id is ‘terms’ and fire the slideDown animation. You should note that these effects are smart enough to know whether the target element is already shown or not. So in this particular example, if the terms element is already being displayed, it won’t try to slide it down on clicking again.

return false;

Finally, this stops the browser following the link’s href (which is the default action).

Here’s the working example

Taking it further

The best way to understand the selectors and how they work is by injecting jQuery (using the bookmarklet) in to a page and testing out selecting using firebug.

Demo

If you find this demo doesn't work as expected, it's possibly due to the demo running from within an iframe. Try running the demo in it's own window.

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>jQuery for Designers - CSS</title>
    <style type="text/css" media="screen">
    <!--
      BODY { margin: 10px; padding: 0; font: 1em "Trebuchet MS", verdana, arial, sans-serif; }
      BODY { font-size: 100%; }
      H1 { margin-bottom: 2px; font-family: Garamond, "Times New Roman", Times, Serif;}
      DIV.container { margin: auto; width: 90%; margin-bottom: 10px;}
      TEXTAREA { width: 80%;}
      FIELDSET { border: 1px solid #ccc; padding: 1em; margin: 0; }
      LEGEND { color: #ccc; font-size: 120%; }
      INPUT, TEXTAREA { font-family: Arial, verdana; font-size: 125%; padding: 7px; }
      LABEL { display: block; margin-top: 10px; } 
      IMG { margin: 5px; }
      DIV.submit {
        background: #eee;
        border: 1px solid #ccc;
        border-top: 0;
        padding: 1em;
        text-align: right;
        margin-bottom: 20px;
      }
      #terms {
          display: none;
      }
    -->
    </style>

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

    <script type="text/javascript">
    <!--
    $(document).ready(function () {
        $('A.reveal').click(function () {
            $('#terms').slideDown('fast');
            return false;
        });
    });
    //-->
    </script>
  </head>
  <body id="page">
    <div id="doc">
        <h1>jQuery for Designers - CSS</h1>
        <p>This is a simple registration form.  If user clicks on the terms and conditions it will reveal the terms.</p>
        <p>If JavaScript is turned off, the link will open as usual (in a new window since we're using a transitional doctype) or with JavaScript enabled, it will slide down.</p>
        <fieldset>
            <legend>Register</legend>
            <div>
                <label for="name">Name:</label>
                <input type="text" name="name" value="" id="name" />
            </div>
            <div>
                <label for="email">Email:</label>
                <input type="text" name="email" value="" id="email" />
            </div>
            <a class="reveal" rel="terms" href="lorem.html">Terms and conditions</a>
            <div id="terms">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
        </fieldset>
        <div class="submit"><input type="submit" name="register" value="Register" id="register" /></div>
    </div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-1656750-8";
urchinTracker();
</script>
  </body>
</html>

Comments

  1. Jim On 7th December 2007 at 20:12

    Of course you can also do:

    $('.hidden').css('display', 'none');

    I’ve always wondered if there is any speed difference between that and $(’.hidden’).hide();

  2. Tom On 5th February 2008 at 03:02

    Perhaps I’m doing something wrong, but I can’t seem to get binding a click handler to elements of a certain class to work. I’m using jquery 1.2.2 and this code

    $(”classname”).click(function(){ //some things });

    html is

    Any ideas?

    TIA, Tom

  3. Tom On 5th February 2008 at 03:02

    I actually put the wrong code in my previous comment, should be

    $(”img.classname”).click(function() { //stuff });

    My html is a simple img with the class classname. I’ve tried this on anchor tags as well to no avail.

  4. Remy On 5th February 2008 at 09:02

    @Tom - the second code looks right, so my bet is that it’s not wrapped in a ‘ready’ statement:

    $(document).ready(function () {
      $(”img.classname”).click(function() { /*stuff*/ });
    });
  5. prisca On 27th April 2008 at 16:04

    Hi,

    thanks for a great site :) learning a lot on here ;)

    I’ve got a problem though with controlling this sliding down effect in a very specific manner… - as I’m new to this I would really appreciate any help, or pointers…

    I’m collecting my samples on this page here: http://dev.eyedea.eu/jquery/pages/slidepanel.html

    Basically, I would like to control the sliding element which reveals my content. I managed to get it working - it slides down fine. But I would like to stop it once it reaches a certain position, ie the very bottom of the window, and then assign it the CSS property of fixed (allowing page content to scroll behind it).

    My sample #6 works with a final result of how the page should look - m problem is that the panel slides out of the window entirely, then jumps into position.

    I think I am close - but cannot figure out to stop the sliding motion at the right moment (and if statement of some sorts I imagine). So the whole thing looks very clumsy … my JS code (in addition to the JQuery link):

    $(document).ready(function(){
            $("#wrap").hide();
            $(".btn-slide").click(function(){
            $("#wrap").slideDown();
            $("#wrap").slideDown("slow");
            $("#wrap").slideDown(function () { $("#footer").css({ height: "84px", position: "fixed", bottom: "0" }); });
            return false;
        });
    });

    Sorry to go on so long - but I have been trying to find a solution desperately and was trying to explain as clearly as possible. Any thoughts would be greatly appreciated….

  6. Edwin On 17th August 2008 at 13:08

    Great introduction into jQuery, thank you very much!

Leave your own comment
  • http://