1

I have some anchors on a site I'm playing with and I'd like them to scroll to anchors instead of doing a sudden jump to the anchor. I've tried several posted solutions here on stack overflow but haven't been able to get them to work. Am I doing something wrong?

I've tried this code and several like it but they don't seam to work:

$('a').click(function(){
$('html, body').animate({
    scrollTop: $( $(this).attr('href') ).offset().top
}, 500);
return false;
});

The site can be found here and currently only the 'about us' item is anchored: http://jsfiddle.net/pnKu2/

3 Answers 3

3

First instead of selecting all anchors, you should select just your navigation IE:

$('.menu-hover-underline').click(function(){
    return false;
});

Next extend this functionality to include the scroll

$('.menu-hover-underline').click(function(){
    var divId = $(this).text().toLowerCase();
    $('html, body').animate({
        scrollTop: $("#"+divId).offset().top
    }, 500);
    return false;
});

See jsfiddle http://jsfiddle.net/pnKu2/2/

Please note I updated your div Ids since all but the about div were id="title".

5
  • The code works perfectly in jsfiddle but the second I uplaod it to my test server it doesn't work. I took your exact code and tried uploading that too but still didnt work, am I forgetting something?
    – Tyharo
    Commented Aug 1, 2014 at 15:10
  • Did you copy the html as well, are you sure jQuery is setup on your site? Commented Aug 1, 2014 at 15:13
  • I did copy the html and yes jquery is setup, oddly id didn't work.
    – Tyharo
    Commented Aug 1, 2014 at 15:16
  • Have you checked your browser console to see if there are any JS errors? Commented Aug 1, 2014 at 15:16
  • Thanks for the assistance though Michael, I greatly appreciate it!
    – Tyharo
    Commented Aug 1, 2014 at 15:47
1

Try this

$(function() {
    $('a').click(function(e){
        var top = $( $(this).attr('href') ).offset().top;
        $('html, body').animate({
            scrollTop: top
        }, 500);
        return false;
    });
});
1

you could try like this:

$('a').click(function(e){
     var href = $(this).attr("href");
     var offsetTop = href === "#" ? 0 : $(href).offset().top;

     $('html, body').stop().animate(
     { 
       scrollTop: offsetTop
     }, 1000);

     e.preventDefault();
});

DEMO

3
  • This will work, but I think selecting every anchor is poor practice and will bite you at some point in the future. Commented Aug 1, 2014 at 14:56
  • No luck, thanks for the quick repose though. All the examples ive found have worked but once I throw the js into my html page it doesn't seam to work.
    – Tyharo
    Commented Aug 1, 2014 at 14:57
  • @MichaelBearjaws agree Commented Aug 1, 2014 at 15:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.