javascript – Anchored Smooth Scroll Script jumping-ThrowExceptions

Exception or error:

I’m attempting to implement a smooth scroll with JS but all I’m getting from the anchored points is a sharp jump, not a smooth transition. Here is the code, I’m pretty certain I’ve got the syntax right, although evidently not, as it’s not working. The two elements I’m trying to link, plus the script.

  <div id="crumbs1">
   <a href="#anchor1"></a>
   </div>


'<div class="poem">
<div id="poem-list1">
<a href="/Crows">Black Crows</a>
<a name="anchor1" id="anchor1"></a>
</div>'

`$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
             scrollTop: target.offset().top
        }, 1000);
        return false;
    }
}
How to solve:

If you don’t (absolutly) have to use anchors (and you can control the IDs), you could try something like:

(html)

<div id="q1" class="question"><p id="p1" class="dp1">Anchor 1</p></div>
<div id="q2" class="question"><p id="p2" class="dp2">Anchor 2</p></div>
<div id="q3" class="question"><p id="p3" class="dp3">Anchor 3</p></div>

<div id="r1" class="result"><p id="" class="">Response 1</p></div>
<div id="r2" class="result"><p id="" class="">Response 2</p></div>
<div id="r3" class="result"><p id="" class="">Response 3</p></div>

and
(script)

$('div[id*=q]').click(function () {

var $this = $(this).attr('id');
var $nmb = $this.substr(1);
var $target = 'r' + $nmb;

    if ($target.length) {

        var $target = '#' + $target;
        var thisTarget = $($target).offset().top;

        $('html,body').animate({
            scrollTop: thisTarget
        }, 1000);
        return false;
    }

});

Leave a Reply

Your email address will not be published. Required fields are marked *