How to add a "Back to top" link at the bottom of the <div>, the browser window is shorter than the page using jquery?
How to add a βTopβ link at the bottom of the browser window shorter than the page using jquery?
<div id="mainContent"> <p>Some content</p> </div> If some content is larger than the browser window (I mean, if there is a vertical panel on the page), then I want to add Back to top 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 the browser has a vertical scroll bar and the user goes down on the page, then I want to show the "Up" link.
Write down the code that will be run when the page finishes loading:
$(function(){ if( $(window).height() < $("#mainContent").height() ) { $("#mainContent").append('<a href="#mainContent">Back to top</a>'); } }); It is as simple as it can be; we use the jQuery height method to find out if we need a backlink and add it if we do this in the document.ready callback . The return link uses the id attribute of the same div that contains it to return the user to the top of the page. (If this main content div is not at the very top of the page, you need to create a separate div with its own id, which is: this div can be empty if it has an id attribute.)
Plain 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>