noid noid - 1 year ago 53
Ajax Question

jquery code doesn't work in ajax loaded content

Yes, I looked trough same articles here, and google helped. But I'm a designer, not a coder. I can copy\paste some code, even change something, but this problem is too hard for me.

So, I have news on my main page, and when you scroll down, next page loads with ajax. There is a script, that shows\hides rating bar for every post. But this code doesn't work inside the loaded content. Please, fix it, if it's not to hard for you.

p.s. I've tried to look into on(), or live, but as I sad before, not my level.

$(document).ready(function() {

var element = $('#dle-content .main-news');
for (i=0; i<element.length; i++)
{
$(element[i]).addClass('news-'+i);
}

$('#dle-content .main-news').hover(
function() {
$('.main-news-hidden').stop(true);
$(this).find('.main-news-hidden').animate({
'bottom':'0'
},400
);
}, function() {
$('.main-news-hidden').stop(true);
$(this).find('.main-news-hidden').animate({
'bottom':'-120'
}, 0);
$('.main-news-hidden').stop(true);
});

$('.top-news li').hover(
function() {
$('.top-news-hidden').stop(true).fadeOut(0);
$(this).find('.top-news-hidden').animate({
'opacity':'1'
},400, function()
{
$(this).fadeIn();
}
);
}, function() {
$('.top-news-hidden').stop(true);
$(this).find('.top-news-hidden').fadeOut(100);
});

var element2 = $('.top-news li');
for (i=0; i<element2.length; i++)
{
$(element2[i]).find('.list').append(i+1);
}


});

Answer Source

Try to include your code in ajax html data , or you can add your script in done function after the html appended.

$.ajax({
  url: "yourUrl",     
}).done(function(data) {
   $("#yourId").html(data);   // Solution 1 :  your content is loaded with ajax, Also this data has your jQuery script
   // Solution 2:  Now start you can call your script via function or add directly here (only html data is needed)
   yourFunction();
   //Solution 3: Now add your jquery code directly
   $(".someClass").click(function(){
     //events
   });
});

These are three differents ways to accessing ajax data with jQuery.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download