Using jQuery’s .data() feature

jQuery has a feature that allows you to assign arbitrary data to DOM elements by way of the data storage methods.  I ran into a scenario today where this feature came in very handy.  Here is how the process works:

  1. The user clicks a checkbox in a list
  2. The checkbox’s parent <li> element is hidden using the “highlight” effect
  3. A new <li> element is created in a different list to show the user’s selection

The problem is the use of the highlight effect.  It was possible that a user could click on the checkbox twice (quickly) – which would perform step #3 twice!  Thus I would end up with 2 identical elements in the “selected” list.

I’m certain there are probably a zillion different ways to handle this scenario – but this is the one I chose…

Using the .data() method on the elements, I ended up with this code:

$('#available_container').find('input:checkbox').data('enableclick',true).click(function()
{
  if ($(this).data('enableclick'))
  {
    $(this).data('enableclick',false);
    $(this).parents('li').hide('highlight');
    add_item(this); //adds the new item to the "selected" list
  }
});
//here is the function when items in the "selected" list are clicked
$('#available_container')
  .find('li:has(input:checkbox[value=' + id + '])').show('highlight')
  .find('input:checkbox').data('enableclick',true);

This seemed the simplest way to temporarily disable the “click” event while the <li> was hiding itself and it works pretty well.

About Jon Trelfa

I live in Detroit, Mi.
This entry was posted in Code and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>