0

I have the following HTML

<div class="anchors">
  <a href="#one">One</a>
  <a href="#two">Two</a>
  <a href="#three">Three</a>
</div>

<a name="one"></a>
<a name="two"></a>
<a name="three"></a>

When clicking an anchor link, I want to scroll to the position of the corresponding <a> tag. For example if I click <a href="#two">Two</a> the window should scroll to <a name="two"></a>

I tried the following js:

    $(".anchors a").click(function(e) {
      e.preventDefault();
      var $this = $(this),
      anchor = $this.attr('href').replace('#', ''),
      dest = $("a[name='" + anchor + "']");
      $('html,body').animate( { scrollTop: dest.offsetTop }, 'fast' );
    });

Nothing happens on click..

Note: The HTML cannot be modified, just the JS.

$(".anchors a").click(function(e) {
  e.preventDefault();
  var $this = $(this),
    anchor = $this.attr('href').replace('#', ''),
    dest = $("a[name='" + anchor + "']");
  $('html,body').animate({
    scrollTop: dest.offsetTop
  }, 'fast');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anchors">
  <a href="#one">One</a>
  <a href="#two">Two</a>
  <a href="#three">Three</a>
</div>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<a name="one">ONE</a>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<a name="two">TWO</a>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<a name="three">THREE</a>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
<p>---</p>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
CyberJ
  • 1,018
  • 1
  • 11
  • 24

0 Answers0