How to add "Back to top" link at bottom at is browser window is shorter than page, using jquery?
<div id="mainContent">
<p>Some content</p>
</div>
If some content is bigger than browser window ( I mean if vertical bar es on the page) then i want to add Back to top just before closing the div.
<div id="mainContent">
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<a href="#"> Back to top </a>
</div>
If browser has vertical scroll bar and user go to bottom at page then I want to show "Back to top" link.
How to add "Back to top" link at bottom at is browser window is shorter than page, using jquery?
<div id="mainContent">
<p>Some content</p>
</div>
If some content is bigger than browser window ( I mean if vertical bar es on the page) then i want to add Back to top just before closing the div.
<div id="mainContent">
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<a href="#"> Back to top </a>
</div>
If browser has vertical scroll bar and user go to bottom at page then I want to show "Back to top" link.
Share Improve this question asked May 17, 2010 at 17:08 Jitendra VyasJitendra Vyas 153k240 gold badges587 silver badges868 bronze badges2 Answers
Reset to default 3Write some code to run when the page is finished loading:
$(function(){
if( $(window).height() < $("#mainContent").height() ) {
$("#mainContent").append('<a href="#mainContent">Back to top</a>');
}
});
This is as simple as can be; we use the jQuery height method to see whether we need a return link, and add one if we do in our document.ready callback. The return link uses the id
attribute of the very same div
which contains it to take the user back to the top of the page. (If this main content div is not at the very top of the page, you'll need to make a separate div with its own id which is; this div may be empty so long as it has an id attribute.)
Normal HTML:
<div id="mainContent">
<a name="backToTop" />
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<a href="#backToTop"> Back to top </a>
</div>
jQuery: using ScrollTo (http://plugins.jquery./project/ScrollTo)
<div id="mainContent">
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<a href="$(\"#backToTop\").localScroll()">Back To Top</a>
</div>