Building simplicidade.org: notes, projects, and occasional rants

JQuery Love

I'm not a Javascript guru, I just dabble a bit, and most of the time I would only reuse stuff from other persons. Until I spent a weekend with JQuery.

I needed a small JS lib to do some stuff in a application I'm working on. Basic stuff, like edit in place, building HTML live and adding more options to forms.

After looking at the tutorials and "how it works"-kind of pages, I started to try it out.

One of the things I wanted was a dismiss specific paragraphs that we use for success or error messages.

I found an example on the JQuery blog that looked promissing. It would hide the message after 5 seconds. The code is simple:

$(document).ready(function(){
    /* add class timed_fadeout to fadeOut after 5 seconds */
    $('p.timed_fade_out').animate({ opacity: 1.0}, 5000, 'linear', function () {
      $(this).fadeOut("slow");
    });
});

You just need to add a class named timed_fade_out to any <p>.

But this was perfect. I didn't want it to just fade way automagically. I wanted the user to click on a dismiss link. So I wrote this:

$(document).ready(function(){
    /* Add dismiss class to append link that closes box */
    $(' <a class="dismiss" href="#">(dismiss)</a>').appendTo('p.dismiss');
    $('a.dismiss').click( function () {
      $(this).parent('.dismiss').fadeOut('slow');
      return false;
    });
});
/* CSS: a.dismiss { color:#999; font-size: 80%; } */

And it worked! First try!

The thing about JQuery, is that it fits my brain, and I don't have to think the way the library works. Very cool.