1

I'm current using the solution provided in this answer jQuery scroll to element however, the problem I have is that the element I want to scroll to has been inserted into the dom via ajax so the function does not actually work. I'm assuming that jquery does not know the element exists yet as the page has not actually been reloaded.

I've used things like jquery .delegate in the past for click/onchange events but, I'm not sure if/how I can use something similar so that jquery can find the newly created element.

Any ideas on how I can do this? The code I'm currently using at the moment to do the scrolling is:

$('html, body').animate({ scrollTop: $("#comment_row_"+comment_id).offset().top }, 2000);

Community
  • 1
  • 1
Cliftwalker
  • 359
  • 1
  • 5
  • 13
  • 1
    show code sequence you are trying this with, if element exists when you call this, should work fine. I suspect you are calling it before ajax is completed – charlietfl Mar 04 '12 at 19:47
  • Where are you putting the call to `.animate`? JQuery "knows" about any element added via AJAX, but my guess is you're calling `.animate` before the AJAX call is complete. – Ryan P Mar 04 '12 at 19:49

2 Answers2

1

You should call your scroll function when ajax is complete and the new element is added e.g. in success callback.

  • Thanks, essentially this was the problem. I was calling the scroll function within ajax success but, it was before another function that was required in order to make scrolling work. – Cliftwalker Mar 12 '12 at 15:30
1

AJAX by definition is asynchronous ( first 'A' in 'AJAX') so code after your ajax call will fire before ajax is completed

$('#content').load( 'url.php');
/* ajax hasn't completed when this fires-FAIL*/
$('html, body').animate({ scrollTop: $("#comment_row_"+comment_id).offset().top }, 2000);


$('#content').load( 'url.php', function(){
    /* ajax has completed when this fires-PASS*/                                    
    $('html, body').animate({ scrollTop: $("#comment_row_"+comment_id).offset().top }, 2000);                                       
});
charlietfl
  • 164,229
  • 13
  • 110
  • 143