mono
mono

Reputation: 3

Replace colon in href attribute in JavaScript or jQuery

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;
});

Upvotes: 0

Views: 1168

Answers (3)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

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

Upvotes: 0

Rakesh Kumar
Rakesh Kumar

Reputation: 2853

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

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

Do this:

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

That will remove : from all href

Upvotes: 1

Related Questions