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:
- The user clicks a checkbox in a list
- The checkbox’s parent <li> element is hidden using the “highlight” effect
- 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);
{
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.










