0

I have a problem handling IDs with a colon in jquery. If there is a colon in an ID the smooth scroll doesn't work.

The HTML

<a href="#fn:1">Go to Footnote 1</a>

<div id="fn:1>Lorem ipsum Bla Bla</div>

JS

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

3 Answers3

1

Do this:

$(function(){
    $('[href]').each(function(){
        $(this).attr('href',$(this).attr('href').replace(/:/g,""));
    });
});

That will remove : from all href

Amit Joki
  • 53,955
  • 7
  • 67
  • 89
0

Try this.

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

Demo Fiddle

Rakesh Kumar
  • 2,648
  • 1
  • 14
  • 32
0

You need to replace # with \\# and : with \\: to escape the character and to make it work:

var $root = $('html, body');
  $('a').click(function() {
      var href = $.attr(this, 'href').replace(/:/g,"\\\\:");
      href = href.replace(/#/,"\\\\#");
    $root.animate({
        scrollTop: $(href).offset().top
    }, 400, function () {
        window.location.hash = href;
    });
    return false;
});

See more about escaping the character here

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187