I'm doing the following:
First, inject HTML into the page (a lot) which then increases the window scrollbar:
$("#XXXX").html("LOTS OF HTML").show();
Then i want to scroll down to the end of the开发者_如何学运维 page:
window.scrollTo(0,$(document).height());
Problem is the page never scrolls down. I did some console.logging and the scrollTo is running before the HTML from the inject html() is run. I tried this in the JS which injects the HTML, I then tried doing the scroll inside the HTML inject but that made no difference.
Any ideas?
As an alternative, here is a different approach (in-case anyone else wants it). I've extended jQuery to add a "ScrollToBottom" function. You can place this in-line with an append/html/text function and will be called after.
The Setup:
;(function($){
$.fn.extend({
scrollToBottom: function(){
window.scrollTo(0,$(document).height());
return this; // allow chaining
}
});
// alias in case you want to call it individually
$.scrollToBottom = $(document).scrollToBottom();
})(jQuery);
The execution:
<head>
$(function(){
var data = '';
for (var d = 0; d < 255; d++)
data += '<p>Hello, world from me!</p>';
$('#demo').html(data).scrollToBottom();
});
</head>
<body>
<div id="demo"></div>
</body>
The result: jsFiddle
EDIT Added an alias to allow it to be called on its own.
Here's something to try:
$.ajax({ //other params //params success: function(data) { $("#XXXX").html(data).show(); } complete: function() { window.scrollTo(0,$(document).height()); } });
The success function runs when the call is successful, and the complete function runs after that, so it might work!
Here's the jQuery docs on .ajax()
精彩评论