Reputation: 2323
My site has a div where content is loaded using the Ajax load method. When any of several links on the home page is clicked, another div on that page is loaded with the content from the selected url. Here's the div:
<div class="main_text">
<div id="C2"><span style="color:black">MTX</span></div>
</div>
Here's the script:
<script>
function ShowAjax(type) {
var filename = "text_" + type + ".htm"
$( "#C2" ).hide().load( filename ).fadeIn(500);
}
</script>
The problem is when I load a new page into a div using the AJAX script shown above, the new page doesn't always load at the top if I had scrolled down on a different page before loading the new page.
I would like the new content to load at the top of the div, not somewhere farther down the page.
I have tried two things so far. The first one is calling scrollTop right after the load:
$(" #C2 ").scrollTop();
The second one is a script at the top of each page to fire on document ready:
<script>
$(document).ready(function(){
$(this).scrollTop(0);
window.scroll(0,0);
console.log("ready to scroll top");
});
</script>
The console.log shows in the dev console, but it doesn't scroll to the top or start at the top.
How can I get the pages to load with the Ajax load method and always appear at the top of the div, with the first line of the text showing instead of starting somewhere down the text (for example, starting on paragraph 3)? Or alternatively how can I force it to scroll to the top after page load?
Upvotes: 2
Views: 374
Reputation: 86
First, you appear to be using scrollTop wrong. Scrolltop with no argument tells you WHERE the scrollbar is on the element, if there is one. Scrolltop with an argument of a height sets the scrollbar. So $("#C2").scrollTop() would probably return 0 since the element probably has no scrollbar. And since you never use the value, it wouldn't do anything. You also probably want to change the scrollbar of the entire document. In reality you would need something like this:
$(document).scrollTop( $(target).offset().top );
Here is an example in jsbin. Scroll down to the bottom to see the buttons to click, and then it will bring the document scroll to bring the target element to the top of the viewport.
It also sounds to me like you are trying to make the element at the top of the page receive the content, regardless of which div was clicked?
If that's the case, then either directly select that element
$('#topElement').hide().load( filename ).fadeIn(500);
Or use one of the actual ajax methods that load is the shortcut for, and target that element in the success callback
$.ajax({
url: filename,
success: function( response ){
$("#topElement").hide().html(response).fadeIn(500);
}
)
Upvotes: 3