James
James

Reputation: 1706

jQuery ScrollTo anchor link but class not ID

How can I modify this so that I can make it scroll to the class rather than an ID?

JS:

// Scroll To # Links
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});

HTML:

<a href="#test">test link</a>

<div class="test" style="margin-top: 1000px;">
    testing content
</div>

JSFIDDLE.

Upvotes: 2

Views: 696

Answers (2)

nirmal
nirmal

Reputation: 2180

try below code

// Scroll To # Links
$('a[href^="#"]').on('click', function(e) {
  e.preventDefault();

  var target = this.hash;
  target = target.replace('#', '');
   var $target = $('.' + target);

  $('html, body').stop().animate({
    'scrollTop': $target.offset().top
  }, 700, 'swing', function() {
    window.location.hash = '#' + target;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#test">test link</a>

<div class="test" style="margin-top: 1000px;">
  testing content
</div>

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can use the fetched value to get the classname and then target the element by class:

 var target = this.hash;
 var $target = $('.'+target.replace('#',''));

Working Demo

Upvotes: 1

Related Questions