javascriptjqueryajaxhashbang

jQuery unrecognized expression with hashbang


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.


Solution

  • You can simply use .replace to escape the ! :

    $(this.hash.replace( /([!])/g, "\\$1" ))