views:

69

answers:

2

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 comes 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.

+2  A: 

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.com/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>
Jason
I don't want absolute positioned "Back to top"
metal-gear-solid
uh, nothing is absolute positioned here? If you're worried about not wanting to hard-code the <a href="".... ect then just make that bit dynamic, ie check if the browser window is too large, then just add the element via JS on-the-fly if you need it. If that doesn't answer, then please clarify?
Jason
+3  A: 

Write 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.)

Eli Courtwright
is `<a name="top"></a>` w3c validated?
metal-gear-solid
@metal-gear-solid: Yes, it passes strict validation on the official W3C validator at http://validator.w3.org/
Eli Courtwright
Actually, it's better to use use the ID attribute - plus that can go on any element. If your header is right at the top you can write `<div class="header" id="top">` and any links to `#top` will go there.
DisgruntledGoat
@Eli Courtwright - but it's not valid in XHTML 1.1 `On the a and map elements, the name attribute has been removed in favor of the id attribute` http://www.w3.org/TR/xhtml11/changes.html
metal-gear-solid
@metal-gear-solid: Thanks for the citation; I've edited my answer to use a div id rather than an anchor name.
Eli Courtwright
@Eli Courtwright - What is the difference between your solution and this solution http://stackoverflow.com/questions/2019532/how-to-show-back-to-top-button-using-jquery-only-if-browser-height-is-shorter-t/2019604#2019604 ?
metal-gear-solid