views:

14

answers:

1

I have a UL that contains items that the user can click on and move from one list to another. I have a function to inspect the list item and move it from one list to another and it works well -- except for one problem.

The list item contains an image (which also responds to the click event). So if my user clicks on the image (essentially a + or - sign that represents add/remove) the function does not work, as the element that it expected as the target is the image, not the list item. How can I delegate the image click to the li that contains it?

The list item is built using struts2 iterator

        <li class="ui-widget-content" id="<s:property value="userId"/>">
            <img src="/images/add_16.png" border="0" alt="add"/>
            <s:property value="firstName"/>&nbsp;<s:property value="lastName"/>
        </li>   

I tried this...

$("#ul-available li").delegate("img", "click", function(){
        $(this).click();
    });

...thinking that if I click the image I could simply invoke the click event on the list item, but it doesn't work. Any ideas what I am doing wrong, or any other ideas on how to accomplish this would be much appreciated.

Thanks to any/all replies!

+2  A: 

Inside .delegate() this is referring to the <img> still, you need to crawl up to the <li>...using .closest() is a good method, like this:

$("#ul-available").delegate("li img", "click", function(){
  $(this).closest("li").click();
});

.delegate() is also intended to capture clicks, so it's better up on the <ul> instead of on each <li>, I've made this adjustment above.

Nick Craver
That does it. I also tried $(this).parent().click() which also seems to work. How do I keep the click event from continuing? The event fires twice, once for the actual click and once for the click I invoke on the list item...
Griff
@Griff - If you don't want it, you can add a `return false;` at the end to stop the other event bubble :)
Nick Craver
Crap. That makes sense. Although, if I understood you correctly, it's not working. $("#ul-available").delegate("li img", "click", function(){ $(this).closest("li").click(); return false; });
Griff
@Griff - Try this instead (though it's hard to know without seeing your other function): `$("#ul-available li img").click(function(){ $(this).closest("li").click(); return false; });`
Nick Craver
Perfect! That's it. Thanks for the help Nick.
Griff