Ajax load method does not load at top of div - javascript

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?

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.
offset returns an object with top and left properties. Giving the position of the element relative to the document. .position gives the position relative to the parent. Using that top number, you can then use that in scrollTop to change the position of the document.
scrollTop then takes that number (the top position of the element) and scrolls the document (or other element) to that position.
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);
}
)

Related

How to set correct position() of a div that is dynamically positioned

I'm making an api call and displaying the info in a div. When I run $(window).scrollTop($('#div').position().top), it returns a position of top: 267px. When viewing the same div in the browser, its position is actually top: 2058px.
Therefore, when I run the code
window.addEventListener('message',function(event) {
if(window.location.href.indexOf('?queryParam=') > -1) {
$('.button').click(function(){
$(window).scrollTop($('#div').position().top);
});
}
return;
},false);
It scrolls to top: 267px rather than top: 2058px where the div is actually visible in the browser.
My theory is that because the div isn't static and instead is being pulled dynamically via an api call, in the event listener, it only accounts for where the div is positioned during the split second when it's being retrieved and not yet placed correctly within the browser.
You are using position().top to get the div's scroll-position.
But this will give you the div's position relative to its parent element.
While incredibly handy in other cases, in your situation it doesn't give the desired value.
In your case you need the div's position relative to the window, since it is the window that you're scrolling.
For that you need to use offset().top, this will give you an element's position relative to the document, no matter how the element is structured on the page:
$(window).scrollTop($('#div').offset().top);

scroll to top of newly generated div

So in my site, when a button is clicked,I dynamically generate a div, which contains a grid of images. It goes like this:
$('.prod-images').click(function(){
var prodImages = generateProdImagesGrid(this);
$('#prod-images-grid').html(prodImages).show();
});
This works fine. And I have another button which will close this div on click.
Now this div can be taller than the screen and require vertical scrolling. The problem is that because of all the CSS/styles in this page, this div always opens only at the scroll position where it was closed. So when I open it first time, it is scrolled to the top and everything is fine. Now, suppose I scroll this div halfway down and then close it. Next time when it is opened, it opens at that scroll position.
I tried doing:
$('#prod-images-grid').html(prodImages).scrollTop(0).show();
This does not work (at least in chrome) because the div is not fully rendered when the scrollTop() call is executed.
The only way I can make this work is to give a long delay between the div rendering and the scrollTop call like so:
$('#prod-images-grid').html(prodImages).show();
window.setTimeout(function(){
$('#prod-images-grid').scrollTop(0);
},10000); //call scrollTop after 10 seconds
As you can imagine, this is not at all a good solution. Does anyone have any suggestions on how I can render the div so that when its visible, it is scroll to its top position?
Doing:
$('#prod-images-grid').html(prodImages).scrollTop(0).show();
means that it's the <div id="prod-images-grid"> which gets scrolled; since this div has no content, it cannot be scrolled.
Rather do:
$(document).scrollTop(0);
$('#prod-images-grid').html(prodImages).show();
The 0 argument of scrollTop can of course be modified to point to the position of the document where you want your dynamically generated div to show.
You can handle a function after the contents is showing whith this propety of .show():
$( ".target" ).show(interval, handler);
Like this:
$('#prod-images-grid').html(prodImages).show(1, function() {
$('#prod-images-grid').scrollTop(0);
});
(you can change 1 for any other value)

Issues with Fixed div on bottom of page that stops at given place

We needed a footer toolbar that stays at the bottom of the page, and sticks to some area when page is scrolled below that area.
We did achieved this using following script:
fixed div on bottom of page that stops in given place
But there is an issue on some page where the footer toolbar just disappears from the page, and then appear again when page is scrolled down further.
We found that this particular issue appears only on few page, when the page has some contents like Images, Video, or Ajax load other content where the content is filled in (or space is being filled) after page has loaded.
I have no clue how to fix this.
Here is the link from live site with problem page.
http://www.sandiegopchelp.com/services/cellphone-repair/htc/
http://www.sandiegopchelp.com/top-10-tips-to-help-secure-your-computer/
http://www.sandiegopchelp.com/notes-on-the-phablet-does-the-world-need-one/
It is usually more visible on blog posts with many comments. May be due to Disqus comments being loaded after the page has loaded completely.
How does this look?
http://jsfiddle.net/LukeGT/NxSc3/
$(window).scroll(function() {
$('#bar').css('position', 'static');
console.log($('#bar').position().top);
console.log($(window).scrollTop() + $(window).height());
if ($(window).scrollTop() + $(window).height() < $('#bar').position().top + $('#bar').height()) {
$('#bar').css('position', 'fixed');
}
});
setTimeout(function() {
$('#extra').show();
}, 1000);​
I simulated the late loading of images by just showing a few extra divs after 1 second. I believe the problem arises from the fact that the height of the page changes after the code for the bar runs, so it's behaving as it should if the page were shorter (without the images/ajax etc).
What I do instead is position the bar in it's place at the bottom of the page each time the page is scrolled, calculate its height from the top there, and compare this with the scroll height. If we're too far up, it positions the bar in a fixed position at the base of the page, and otherwise leaves it alone. It works smoothly in Chrome, but I haven't tested elsewhere.
I guess this is a problem with the $(window).height() function. Check here. For all the dynamic contents like Images, Video or Ajax-loaded content the height is not added to the result of $(window).height() unless it is specified somewhere in the HTML or CSS (and from the referred link I see this happens only in Chrome. You might want to confirm on this though). To those dynamic contents you can either try adding the height attribute in html or height attribute in the corresponding style.
This is not the answer but i have found something while inspecting your website...
This is you actual HTML when its working fine as you want..
<div class="footer-toolbar-container" id="sticky_for_a_while" style="position: fixed; ">
but when it is not working, the Position attribute is changing from Fixed to Relative .
<div class="footer-toolbar-container" id="sticky_for_a_while" style="position: relative; ">
you can check you script for that or post you script here...
At initial state, your div is in position: relative so its offset is based on the container element, not on the total height of the page. The variable stickyOffset is set based on that relative offset, that is why it gets clip down sooner than expected while scrolling and also why it works in your JSFiddle as the container there is the page (Iframe) itself.
In your $(document).ready function, you'll need to add the offset of not only the footer but also the rest of the offset on top of the containing element so that the offset is based on the total page instead of the containing div.
Hope that helps.
By looking at your example on http://www.sandiegopchelp.com/services/cellphone-repair/htc/ using chrome, I can see that your footer disappears when it gets at the "related links" section. At this moment, you set the position of the footer to "relative" so it will replace it in the regular flow of the document and its position is actually below the "related links" section which is why it disappears off screen (below "related links").
but you calculated the position at which it should become relative on page load only where you should have recalculated it after having added the "related links" section as it changes the page height (I understood that you added afterward, am I right?).
Try adding a zero height div just above the position of the sticky div, which will remain at that position as the page resizes, then check that position as you scroll to determine the position where the sticky div should stop.
Finally got it fixed by two techniques, setting explicit height wherever possible using CSS and delaying jQuery function after all images are loaded. Refer this: Delay some jQuery function until all images are loaded completely

JScrollPane not working properly with hidden content

I installed jScrollPane on my website and can't make it work.
My website works as follows: from the main page, pages are loaded dynamically using jQuery's load() method. In the page I load I have the following script to launch jScrollPane:
$(function(){
$('.scroll-pane').jScrollPane();
});
Which seems to be called. No problems so far I guess. The problem is that the page, at the beginning, is not long enough to need a scrollbar. I have hidden content that shows up only on specific actions (i.e. clicking on a button shows the content of a certain paragraph), and when I click to show the content of a hidden div, the scrollbar doesn't appear.
I also tried to call $('.scroll-pane').jScrollPane(); as I show the new content (i.e. in the event that triggers .show() on the hidden div I also call $('.scroll-pane').jScrollPane();) but I had no success with that either.
Can anyone help me?
Thanks
EDIT:
I forgot to mention the structure of the page: I have a div which has class="scroll-pane" and is loaded with the page load and it contains small hidden divs that show up when clicking on particular areas. I would like to add a scroll bar to the div with the class scroll-pane in order to make the content of the showed div scrollable (right now the content stays in the size of the div but it's not scrollable since no jScrollPane scroll bar is shown).
Update:
I tried to put $('.scroll-pane').jScrollPane(); in the callback of the .show() method of my divs and tried to put class="scroll-pane" to those divs that appear, but again nothing is shown (the scroll bar doesn't appear and the div is not scrollable).
Check this demo provided by the developer of the plugin
http://jscrollpane.kelvinluck.com/examples/invisibles.html
When the element is first shown you simply have to (re)initialise the
scrollpane (or you could even use autoReinitialise if you like) and
its width and height will be calculated correctly.
All that you need is
$(function(){
$('.scroll-pane').jScrollPane({autoReinitialise: true});
});
and may be the recent version of the plugin
I suggest to use css visibility property instead auto reinitialising. Each time you call show() method, jScrollPane reinitialises itself. This takes time and has impact on animation.
If you use, say, slide..() methods, then animation starts properly, but scrollable container (and its elements) appears little bit later, and that looks bad.
var wrapper = jQuery('#gallery-album-preview-wrapper');
if (wrapper.css("visibility") == "hidden") {
wrapper.css("visibility", "visible").css("display", "none");
}
if (wrapper.is(":hidden")) {
wrapper.slideDown(1000);
} else {
wrapper.slideUp(1000);
}

Setting HTML page vertical position with JavaScript

I have a HTML page that scrolls up and down (not a lot, but it does scroll). How can I set the scroll position in the page after executing some JavaScript?
I'm using jQuery to inject some additional HTML at the bottom of the page and I'd like to programmatically scroll to the position of that new content after it's added.
Try using window.scroll.
Example:
// put the 100th vertical pixel at the top of the window
<button onClick="scroll(0, 100);">click to scroll down 100 pixels</button>
Another way to do this, so that you have the option:
In the HTML you are adding to the bottom of the page, you can insert a named anchor tag and then change the URL so that the page moves there (FYI: it will not refresh the page).
// add HTML like this, dynamically:
// <a name="moveHere" />
// the javascript to make the page go to that location:
window.location.hash = "moveHere";
Depending on what you are doing, this may or may not be a useful solution.

Categories

Resources