Scipion
Scipion

Reputation: 11888

Replace the behavior of an hash link anchor with Jquery

I have the following bit of code :

                <a href="#anch">Anchor hash link</a>
                <div id="anch">
                  <ul>
                    <li>foo</li>
                  </ul>
                </div>

I can't use anchor hash link for several different redirecting reasons. Is there a way to emulate its behavior with a small jquery script ? (to get rid of the href, and instead having an onClick doing exactly the same ?)

Upvotes: 0

Views: 94

Answers (1)

Phillip
Phillip

Reputation: 6253

To replace the behaviour with jQuery without adding a # to the url:

$('a[href*="#"]').click(function(e) {
  var scrollAnchor = $(this).attr('href');
  $('html, body').scrollTop($(scrollAnchor).offset().top);
  return false;
});

See this bin: https://jsbin.com/tizixapabu/edit?html,js,output

Links still work as usual.

Upvotes: 1

Related Questions