Reputation: 20163
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 comes 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?
Upvotes: 1
Views: 6449
Reputation: 41767
Update
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!
Upvotes: 2
Reputation: 12155
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);
});
}
Upvotes: 0
Reputation: 43245
<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 #
Upvotes: 1
Reputation: 10305
since you use jquery I would do
<a href="#">go</a>
$("a").click(function() {
e.preventDefault(); // cancel's the '#' click event
scrolear('#container');
});
Upvotes: 1