views:

88

answers:

1

This is my first question on SO, so if it seems beyond dumb, please take it easy on me. I have a page with a list of pictures with links for deletion underneath them and with possibility to add more pictures. After each one of this events (that does a #user_gallery load like below, I have to click twice the delete link for it to work. Why is that ?

$('body').delegate(".delete", "click", function(e){
        $('.delete').click(function(ev){
           var pic_id = $(this).attr('id').replace('pic_', '') ;
           $.post(   'unpublish_pics.php',
                     {pic: pic_id, action:'delete'},
                     function(data)
                     {                            
                            $('#user_gallery').load("pictures_display.php");
                     },"json"
                 );
           ev.preventDefault();
        });
        e.preventDefault();
   });

The html is goes something like this.

<div id="user_gallery">    
<div class="image">
   <a rel="gallery" class="img" href="pic.png"><img src="pic.png"></a>
    <a id="pic_1" class="ui-state-default ui-corner-all delete" href="#">Delete</a>
</div>

+4  A: 

You don't need that .click() handler/wrapper underneath, just the .delegate() like this:

$('body').delegate(".delete", "click", function(e){
  var pic_id = $(this).attr('id').replace('pic_', '');
  $.post('unpublish_pics.php', {pic: pic_id, action:'delete'}, function(data) {                            
    $('#user_gallery').load("pictures_display.php");
  },"json");
  e.preventDefault();
});

Currently you're binding a .click() handler for the next click...if you want to perform an action when it's clicked just place the code right in the .delegate() handler.

Nick Craver
Yeah, that did the trick. It seems pretty logical too, so big thanks.
dragosplesca