0

I am using a script for smooth scrolling from here Smooth scrolling when clicking an anchor link (the version where the URL is changed).

It works for all anchors except those that have a . in their ID. So linking to:

  • 1 works

  • 1.1 doesn't work

Any idea of how to fix this?

Code:

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

Demo: http://bagsy.netau.net/rj/rj.html

Community
  • 1
  • 1
Dan
  • 5
  • 3
  • Possible duplicate of [this](http://stackoverflow.com/questions/350292/how-do-i-get-jquery-to-select-elements-with-a-period-in-their-id) – trincot Nov 08 '15 at 15:21

1 Answers1

0

The id should not start with a digit. But if you don't want to change id, you can use this code:

var $root = $('html, body'); 
$('a').click(function() {
    var href = $.attr(this, 'href').replace('#','');
    $root.animate({
        scrollTop: $('[id="'+href +'"]').offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});
Henry Tran
  • 526
  • 3
  • 12
  • Thanks - this worked. HTML5 actually does allow IDs to start with numbers now (though HTML4 didn't). – Dan Nov 08 '15 at 18:26
  • With jQuery, to use any of the meta-characters (such as **!"#$%&'()*+,./:;<=>?@\^{|}~**) as a literal part of a name, it must be escaped with with two backslashes: \\ ([more](http://api.jquery.com/category/selectors/)). In your case, you can also use: `$("#2\\.1")`. – Henry Tran Nov 09 '15 at 02:19