joe
joe

Reputation: 219

bind function to ajax loaded data on() not working jquery

I have this function that works well in my page. the problem is that It doesnt work in results loaded by Ajax.

HTML

  <ul id="container">

    <img src='icons/px.gif' data-src="images.png\" class='lazy-img' />
    <img src='icons/px.gif' data-src="images.png\" class='lazy-img' />
    <img src='icons/px.gif' data-src="images.png\" class='lazy-img' />
    <img src='icons/px.gif' data-src="images.png\" class='lazy-img' />
    <img src='icons/px.gif' data-src="images.png\" class='lazy-img' />
    <img src='icons/px.gif' data-src="images.png\" class='lazy-img' />


         </ul>

JQUERY

 setTimeout( function(){
     $('.lazy-img').each(function() {this.src = $(this).data('src'); 
          }).removeAttr('data-src');
                  }, 800);

How should I bind this function with the container?

Upvotes: 0

Views: 43

Answers (1)

SRK
SRK

Reputation: 3496

$(document).ready(function(){

$('ul#container').on('select',function(){
setTimeout( function(){
     $('ul#container .lazy-img').each(function() {
     this.src = $(this).data('src'); 
          }).removeAttr('data-src');
                  }, 800);
});
$('ul#container').trigger('select');

});

What you can do is bind an event with the ul#container and on document ready trigger that event.

In your AJAX success just trigger that event again!!

$.ajax({
  . 
  .
  success: function(data){
   $('ul#container').trigger('select');
  },
});

Also put this AJAX function in document.ready You can trigger this event wherever you need to call that function.

Try this, hope it will help.

Upvotes: 1

Related Questions