Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

jquery scrollTop and href="#"

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

Answers (4)

Rich O&#39;Kelly
Rich O&#39;Kelly

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

DhruvPathak
DhruvPathak

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

Manuel van Rijn
Manuel van Rijn

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

Related Questions