0

I have some fragments that load on click. I also scroll the page to the top on these links, as found on css-tricks. I get the following error: Uncaught Error: Syntax error, unrecognized expression: #!Fragment_Name

My js

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);//this is where the error is
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html,body').animate({
            scrollTop: target.offset().top
        }, 1000);
        return false;
        }
    }
    });
});

HTML

<li><a href="#!Fragment_Name">Link Text</a></li>

I have tried var target = $($(this.hash)); no joy

Everything still works, I just want to know how to fix this and remove the error from console.

Dirty Bird Design
  • 5,333
  • 13
  • 64
  • 121

2 Answers2

1

You can simply use .replace to escape the ! :

$(this.hash.replace( /([!])/g, "\\$1" ))
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • I replaced var target = $(this.hash); with var target = $(this.hash.replace( /([!])/g, "\\$1" )); The error now reads Uncaught Error: Syntax error, unrecognized expression: [name=!Fragment_Name] – Dirty Bird Design Mar 08 '17 at 20:24
  • 1
    @DirtyBirdDesign That's your second selector (`$('[name=' + this.hash.slice(1) +']');`). Just add quotes after the `=` and before `]` : `$('[name="' + this.hash.slice(1) +'"]');` – Karl-André Gagnon Mar 08 '17 at 20:25
  • Excellent! combining the two worked. I dont understand what the /[!]/g does exactly, I know it is escaping the "!" but not why. The second part I get, escaping the "#" in the slice. Thank you very much, great answer! – Dirty Bird Design Mar 08 '17 at 20:37
-1

This is because there is a special character in your JQuery selector. Remove the ! from your href and it will be okay.