I am building a mobile webapp with jquery mobile. Now I want to do a back to top action. Normally you should do it like the code below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Body ID For Top Anchor Demo</title>
</head>
<!-- NOTICE: ID in Body Tag. -->
<body id="top">
<h1>
This Is My Demo
</h1>
<p style="margin-bottom: 3000px ;">
This paragraph has a huge ass bottom margin
so that the page will definitely scoll and
put the following link below the page fold.
</p>
<p>
<!--
This link will jump back up to the ID:top in
the document. Since that is the ID of the body
tag, this link will jump to the top of the page.
-->
<a href="#top">Back To Top</a>
</p>
</body>
</html>
But the # is in jquery mobile used for linking internal pages, so the method above doesn't work. Does anybody know how to do this properly?
Kind regards.
jQuery Mobile has it's own $.mobile.silentScroll() function that scrolls to a particular Y position without triggering scroll event listeners. (http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/methods.html)
If you want to animate the scroll you can use animate to change the scrollTop property of the scroll-able page element (sometimes it's <html> sometimes it's <body>).
//delegate binding to only links that have the `.top` class
$(document).delegate('a.top', 'click', function () {
$('html, body').stop().animate({ scrollTop : 0 }, 500);
return false;
});
Here is a demo using $.mobile.silentScroll(): http://jsfiddle.net/XkjEE/2/
Here is a demo using .animate(): http://jsfiddle.net/XkjEE/1/
Docs:
scrollTop(): http://api.jquery.com/scrolltop/delegate(): http://api.jquery.com/delegate/stop(): http://api.jquery.com/delegate/animate(): http://api.jquery.com/delegate/You can set data-ajax="false" on a link or button widget to stop jQuery Mobile from hijacking the link clicks and stopping the default behavior of the links.
Make your link look something like this:
<a data-ajax="false" data-role="button" href="#top">TOP</a>
Here is a demo: http://jsfiddle.net/XkjEE/
I was looking for something similar today and came across this which might work http://jsfiddle.net/b4M66
The button only fades in once you start scrolling down the page and disappears once you return to the top of the page.
jQuery:
$(function() {
$(window).scroll(function() {
if($(this).scrollTop() != 0) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('#toTop').click(function() {
$('body,html').animate({scrollTop:0},800);
});
});
CSS:
#toTop { position: fixed; bottom: 50px; right: 30px; width: 84px; background-color: #CCC; cursor: pointer; display: none; }
HTML:
<div id="toTop">Back to Top</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With