Reputation: 61
Links jump to bottom and top but won't smooth scroll even though I'm sure JS is working.
JS:
$.fn.ready(function() {
// Smooth scroll to top.
$("a[href=#top]").live("click", function(e) {
$("html,body").animate({scrollTop:0}, 1000);
e.preventDefault();
});
// Smooth scroll to bottom.
$("a[href=#bot]").live("click", function(e) {
$("html,body").animate({scrollTop:$(document).height()}, 1000);
e.preventDefault();
});
});
HTML:
<a href="#bot" id="botlink" title="Go to bottom">↓</a>
<a href="#top" id="toplink" title="Go to top">↑</a>
Upvotes: 0
Views: 693
Reputation: 15951
check this fiddle it might help you
$("a[href=#top]").on("click", function (e) {
//alert("top")
$('html, body').animate({
'scrollTop': 0
}, 1000)
event.preventDefault();
});
// Smooth scroll to bottom.
$("a[href=#bot]").on("click", function (e) {
// alert("bottom")
var a = $(document).height()
$('html, body').animate({
'scrollTop': a + 'px'
}, 1000)
event.preventDefault();
});
Upvotes: 0
Reputation: 1326
I guess you're using an old version of jQuery if you use "live" event. Since you want to go on top/bottom, you know that they're on certain positions ( top = 0, bottom = document.height ). A working jquery code will be like :
jQuery(document).ready(function($){
$('#botlink').add( $('#toplink') ).on( 'click', function( e ){
e.preventDefault();
var $btn = $(this).attr( 'id' ).replace('#', '');
var move_to = $btn === 'botlink' ? $(document).height() : 0;
$('body').animate({
scrollTop : move_to
}, 'slow');
});
});
The code above checks when user clicks #botlink
or toplink
. Inside move_to
variable it checks which button was clicked ( read about "short if" ) and calculate when page should go. To have a working effect, you need to animate both, html
and body
.
Actuall it works just on body
. You also have a js fiddle here (i've foced body to grow on 1200px to be able to see the effect)
Upvotes: 1