Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognized expression: a[href^=#]

I am trying to make a trivial "scrollTo element" function.

Console shows me the error: Syntax error, unrecognized expression: a[href^=#] for a[href^=#] code

According to the reply on this question I wrapped the hash symbol into double quotes, but now console shows Unexpected token ILLEGAL for that.

Please, explain what I am doing wrong and how to fix it.

Here's my code:

$(document).on('click', 'a[href^=#]', function () {
        $('html, body').animate({ scrollTop:  $('section[data-target="'+this.hash.slice(1)+'"]').offset().top }, 1000 ); 
        return false;
    });
menu {
  background-color: #1abc9c;
  height: 50px;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  margin: 0;
  padding: 0;
}


menu ul li {
  display: inline-block;
  padding: 0 15px;
}

menu ul li a {
  color: #333;
  text-decoration: none;
}


section {
  height: 300px;
  padding: 60px 0 0 45px;
}

.one {
  background-color: #3498db;
}

.two {
  background-color: #e74c3c;
}

.three {
  background-color: #f39c12;
}

.four {
  background-color: #2c3e50;
}
<menu>
  <ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
    <li><a href="#four">Four</a></li>
  </ul>
</menu>

<section class="one" data-target="one">Section One</section>
<section class="two" data-target="two">Section Two</section>
<section class="three" data-target="three">Section Three</section>
<section class="four" data-target="four">Section Four</section>

and the same in JSFiddle

like image 893
Alexandr Belov Avatar asked Mar 31 '16 19:03

Alexandr Belov


1 Answers

Since # is a metacharacter of jquery, you have to wrap it by using quotes or you have to escape it by using \\,

$(document).on('click', 'a[href^="#"]', function () {

or

$(document).on('click', 'a[href^=\\#]', function () {

DEMO

like image 157
Rajaprabhu Aravindasamy Avatar answered Sep 21 '22 11:09

Rajaprabhu Aravindasamy