views:

751

answers:

3

I have an unordered list of items, something like this, shortened for brevity:

<div id="elementsContainer">
  <ul>
    <li><a>One</a></li>
    <li><a>Two</a></li>
  </ul>
</div>

I have the list styled up, but these 3 styles deal with background images for the list items:

#elementsContainer ul li {
    list-style:none;
}
#elementsContainer a {
    background: transparent url(/images/icons/bullet_delete.png) no-repeat 5px 50%;
}

#elementsContainer a:hover,
#elementsContainer a:focus,
#elementsContainer a:active {
    background:#fff url(/images/icons/delete.png) no-repeat 5px 50%;
}

The list looks great - it puts a little delete icon to the left of the text for each list item. However, I am looking to use jQuery (1.3) to handle the click events for each item, and I would like separate functionality between the background image of the list item and the text of the list item. If I click the image, I want to delete the item. If I click the text, I want to edit the item.

I started using something like this:

$("a").live("click", function(event){
  alert( $(this).text() );
});

But I do not see anything in $(this) or "event" that I can determine if I am clicking the text or the image.

Yes, I know I could just have a separate "img" tag and handle the click on that separately. I'll go that route if that is the only option. I just want to know if there is some way to make it work on the background-image.

Thanks in advance!

+5  A: 

Go with the IMG tag. The best you could do it detect a click on the LI element itself, which would end up being messy. An IMG tag (and even an A tag around it for semantic goodness and nicely-degrading pages) would work best.

You shouldn't have much issues styling it to look the same using an IMG within the LI, I do something similar all the time within lists where I need delete/edit icons.

Parrots
+2  A: 

You can't differentiate a click on the background image, since as far as the DOM is concerned, it's not really there. All you have is the a element itself (which happens to be presented with your background image), and its onclick handler will fire as long as you click anywhere inside the tag, text or not.

It probably is best to use an img tag (or some other separate tag) and handle the click on that separately, as you concluded in your write-up.

Adam Bellaire
+1  A: 

what you could do for the desired effect is to put a span with some spaces in the area that the delete image will eventually appear, and then hook the event to the click of that span.

Jon Erickson