tags:

views:

45

answers:

2

I am sorry if this is a lil unclear, but I am having problems conceptualizing what I want todo.

I am using have a list of div's like so

  <div id="1" class="ajax_category">
     <p> Blah </p>
  </div>

There is a javascript set to make a ajax request to a url when the div id is clicked. This works fine, but I am having to repeat myself for each div on the page. Here is the javascript snippet...

 $('#1').bind('pageAnimationEnd', function(e, ajax_item_1){
 if (!$(this).data('loaded')) {
    $(this).append($('<div><img class="loading" src="../../img/loading.gif"><div>').
      load('ajax/load_item/1 #ajax_item_1', function() { 
        $(this).parent().data('loaded', true);
       }));
      }
     });

I would like to somehow modify this script to be triggered by a click of the div's class and then append the loading div to that div's id. The grab the div id and make the ajax request referencing the div id in the jq 'load' url.

Please let me know if this is unclear or if you have any other questions.

Thanks, Peter

A: 

Bind to "div.ajax_category" instead. Then, use the ID of the element that you get in the event arguments. Create the strings you need something like this:

var toLoad = "ajax/load_item/" + elementId + " #ajax_item_" + elementId;

You may also do better with the newer "delegate" event handling in jquery. It avoids lots of the cost involved with calling "bind" on many elements.

John Fisher
A: 

You should be able to do this using delegate:

$('#container').delegate('.ajax_category','click',function(){
    if (!$(this).data('loaded')) {
        $(this).append(
            $('<div><img class="loading" src="../../img/loading.gif"><div>')
                .load(
                    'ajax/load_item/' + this.id + ' #ajax_item_' + this.id, 
                    function() {
                        $(this).parent().data('loaded', true);
                    }
                )
        );
    }
});

Note that this presumes that your elements with the class ajax_category are wrapped in a div with the id container.

This has a significant performance advantage over binding to ajax_category itself because it only involves one bind, rather than several. Binding is relatively expensive in terms of performance.

lonesomeday