views:

88

answers:

1

I am having trouble figuring out how to use the JQuery delegate function to do what I require. Basically, I need to allow users to add Panels (i.e. divs) to a form dynamically by selecting a button. Then when a user clicks a button within a given Panel, I want to be able to to something to that Panel (like change the color in this example). Unfortunately, it seems that references to the JQuery traversing functions don't work in this instance. Can anybody explain how to achieve this effect? Is there anyway to bind a different delegate to the each panel as its added.

$('.addPanels').delegate('*', 'click', function() {  
    $(this).parent.css('background-color', 'black');  
    $('.placeholder').append('<div class="panel"><a href="#" class="addLink">Add item</a></div>');  
 });  

<div class="addPanels">  
    <div class="panel">   
        <a href="#" class="addLink">Add item</a> text</div>  
       <div class="placeholder"/>  
    </div>  
</div>  
+1  A: 

parent is a method, not a property; so it needs to be invoked (parent())

The first parameter for the delegate method is the selector; so you're capturing a click event on any element within .addPanels.

$('.addPanels').delegate('.addLink', 'click', function(event) {
    var panel = $(this).closest('div.panel');

    panel.css('background-color', 'black');
    panel.find('.placeholder:first').append('Add item');

    event.preventDefault();
});

Would be how I'd choose to do it. ("closest" documentation )

Matt