Home > OS >  jquery unrecognized expression div
jquery unrecognized expression div

Time:01-19

I have a Syntax error, unrecognized expression. I use a set of links to change to a div on the same page and sent a variable with it.

<a href="?taal=<?PHP echo $taal; ?>#Home">Voorpagina</a>
<a href="?taal=<?PHP echo $taal; ?>#Updates">Updates</a>
<a href="?taal=<?PHP echo $taal; ?>#About">Over mij</a>

$taal is the language the user choose, like NL, EN…

After the user clicks, get this in action:

$('a').click(function (e) {
  $('html, body').animate({
    scrollTop: $($(this).attr('href')).offset().top}, 500);
});

Everything works but I get the next error in my console:

Uncaught Error: Syntax error, unrecognized expression: ?taal=nl#Updates
at Sizzle.error (jquery-3.6.0.js:1681:8)
at Sizzle.tokenize (jquery-3.6.0.js:2381:11)
at Sizzle.select (jquery-3.6.0.js:2842:20)
at Function.Sizzle [as find] (jquery-3.6.0.js:898:9)
at jQuery.fn.init.find (jquery-3.6.0.js:3099:11)
at new jQuery.fn.init (jquery-3.6.0.js:3209:32)
at jQuery (jquery-3.6.0.js:161:10)
at HTMLAnchorElement.<anonymous> (?taal=nl:175:24)
at HTMLAnchorElement.dispatch (jquery-3.6.0.js:5430:27)
at elemData.handle (jquery-3.6.0.js:5234:28)

How can I resolve this error? By the way, if I remove the <?PHP echo $taal; ?> variable in the links above (first code), the error is gone but I need that variable for further navigation.

I’ve tried to rebuild the code, removed $taal and the error was gone but I need that variable.

Thanks in advance.

CodePudding user response:

You need a selector as the argument to $(). The selector is after the # in the href, e.g. #Home or #Updates. You need to extract that from the href attribute.

$('a').click(function (e) {
  let href = $(this).attr('href');
  let target = href.split('#')[1];
  $('html, body').animate({
    scrollTop: $(`#${target}`).offset().top}, 500);
  });
});

CodePudding user response:

You are using the whole url, you want to just use the hash portion.

$('a').on('click',function (e) {
  e.preventDefault();
  console.log(e.target.hash);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="?taal=example.com#A">A</a>
<a href="?taal=example.com#B">B</a>
<a href="?taal=example.com#C">C</a>

CodePudding user response:

I've fixed the issue. In the code do I check now if $taal exists or not. If not, then I use my old jQuery link code, the code on the top of this page. If $taal does exist, then I split the URL variables and do I use Barmar's code. Thanks for all your help.

  • Related