I use this function to scroll to a desired container:
function scrolear(destino){
var stop = $(destino).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop+'px'}, delay);
return true;
}
The problem es when is used like this:
<a href="#" onclick="scrolear('#container');">go</a>
Because the href="#"
makes body to scroll to top of page.
Is there a way to prevent this?
I use this function to scroll to a desired container:
function scrolear(destino){
var stop = $(destino).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop+'px'}, delay);
return true;
}
The problem es when is used like this:
<a href="#" onclick="scrolear('#container');">go</a>
Because the href="#"
makes body to scroll to top of page.
Is there a way to prevent this?
Share Improve this question edited Nov 15, 2011 at 11:47 Anne 27.1k9 gold badges67 silver badges71 bronze badges asked Nov 15, 2011 at 11:46 Toni Michel CaubetToni Michel Caubet 20.2k58 gold badges218 silver badges388 bronze badges4 Answers
Reset to default 2Update
Consider using javascript to progressively enhance your site rather than relying on it for the site to function correctly. In your example this would be achievable by the following:
HTML:
<a href="#container">go</a>
Javascript:
$(function() {
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
var stop = $(target).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop + 'px'}, delay);
});
});
This would intercept clicks on all links where the href started with a # and add in the animation for you. If the user did not have javascript enabled clicking the link would still take them to the correct place.
Hope this helps!
<a href="javascript:void(0);" onclick="scrolear('#container');">go</a>
This will just assign a javascript function to the href, which will do nothing at all,so no page scroll happens like with #
since you use jquery I would do
<a href="#">go</a>
$("a").click(function() {
e.preventDefault(); // cancel's the '#' click event
scrolear('#container');
});
corrected answer from @rich.okelly
function scrollTosec(){
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
var stop = $(target).offset().top;
var delay = 200;
$('body').animate({scrollTop: stop + 'px'}, delay);
});
}