Wednesday, 21 July 2010

jquery - the trigger method

Having recently had to work on a client website where jquery wasn't available, it was really apparent just how useful this library is and how pleasureable it makes working with JavaScript. Having to resort back to getElementById and getElementsByClassName was painful in comparison.

Today I discovered and made use of yet another useful feature - the trigger method which enables an action on one element to fire the functions associated with events on another.

I had a simple accordion style user interface that looked like this:

On clicking the cross on the right a panel below would expand and display the content.

The mark-up looked like this:

    1 <ul id="list">

    2     <li>

    3         <div class="head">Title</div>

    4         <a href="">+</a>

    5         <ul>

    6             <li>Content one</li>

    7         </ul>

    8     </li>

    9 </ul>

And I had a function that carried out the toggling of the display like this:

    1 $("#content ul.list a.toggle").click(function() {

    2     if ($(this).next().is(":visible")) {

    3         $(this).next().hide("fast");

    4         $(this).text("+");

    5         $(this).parent().removeClass("on");

    6     } else {

    7         $(this).next().show("fast");

    8         $(this).text("-");

    9         $(this).parent().addClass("on");

   10     }

   11     return false;

   12 });

As you can see the code relies on the position of the link element (it's looking for the next element to expand) and makes some styling changes to the link itself.

So when the designer asked to make the whole bar clickable this was a bit annoying, as it looked like I would to replicate the function and adapt it to cope with a click on the bar instead of the cross.

But with jquery trigger you can fire an event on another element, so adding this small addition to the function provides the means for a click on the div element firing the function associated with the click of the link.

    1 $("#content ul.list div.head").click(function() {

    2     $(this).next().trigger("click");

    3 });

And the last line can be simplified further to:

  1 $(this).next().click();