2

I want to apply this function to content which is loaded by ajax. Thing is, the function is not working on such content. Is there somehow a workaround for this each-function?

     $(".liquidcam").each(function(index) {
          if( (!this.width || !this.height) ) {

         $(this).parent().parent().hide("fast");
        }

        $(this).error(function() {

         $(this).parent().parent().hide("fast");
        });



  });
Mark Henry
  • 2,649
  • 7
  • 40
  • 48

2 Answers2

1

I faced the same problem recently. Most of plugins need to be applied to elements by calling them in $(document).ready(), I wanted to call the same function not only for content which was there just after the document was loaded, but also for those elements which arrived by Ajax call later.

After googling a while I found two types of recommendations: 1. To bind to final event of every ajax call. 2. To bind to some element specific event, (like focus()) to run your code.

In the first case you need to take care about it in your ever ajax call. The second did not worked for all cases well.

So my solution is to call the same function from $(document).ready() and $(document).ajaxSuccess(). In this case I need to prevent one and the same manipulation to happen to the same control twice. SO I used a special class I am applying to all visited elements.

function doOnReady() {
    $(":input[data-autocomplete]").each(function () {
        //Check wether allready visited
        if (!$(this).hasClass('visited-by-on-ready')) {

            //Do your staff
            $(this).autocomplete({
                source: $(this).attr("data-autocomplete"),
            });
            //mark as visited
            $(this).addClass('visited-by-on-ready');
        }
    });
}

$(document).ready(doOnReady);
$(document).ajaxComplete(doOnReady); 
George Mamaladze
  • 7,593
  • 2
  • 36
  • 52
  • 1
    I am doing it almost the same way. I just added an argument to the `doOnReady()` supplying a selectot to scope every call in it to. This way I can e.g. `doOnReady('#modal-content')` to apply everything to just the dynamically loaded modal content, and `doOnReady('body')` on load. – pdu Sep 14 '12 at 15:31
1

Building on what achitaka-san said, with the latest jQuery you can just do...

$(document).on('ready ajaxComplete', function() {
    // ...attach your events/plugins here
});

Which, I think is a bit cleaner and easier to follow/extend if you ever needed to. You need to be careful about creating loops though (for example if you fire some AJAX calls in your 'ready' handler!).

Tom Davies
  • 899
  • 6
  • 20