0

l found this script (that l don't understand) :

function scrollTo(c,e,d){d||(d=easeInOutQuart);var a=document.documentElement;if(0===a.scrollTop){var b=a.scrollTop;++a.scrollTop;a=b+1===a.scrollTop--?a:document.body}b=a.scrollTop;0>=e||("object"===typeof b&&(b=b.offsetTop),"object"===typeof c&&(c=c.offsetTop),function(a,b,c,f,d,e,h){function g(){0>f||1<f||0>=d?a.scrollTop=c:(a.scrollTop=b-(b-c)*h(f),f+=d*e,setTimeout(g,e))}g()}(a,b,c,0,1/e,20,d))};
function easeInOutQuart(t) {
    return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t
}

But it works perfectly on my attempt to scroll to the top :

document.getElementById('toTop').onclick = function() {
    scrollTo(0, 2500, easeInOutQuart);
}

DEMO THERE

Well, can someone help me please to rectify the script below which doesn't work :

var  elements = document.querySelectorAll('.nav li a'),
     target;
for (var i = 0; i < elements.length; i++) {
     var element = elements[i];
     element.addEventListener('click', function(e) {
          target = this.getAttribute('href');
          console.log(target);
          scrollTo(target, 2500, easeInOutQuart);
     });
}

ATTEMPT LINK NAV

target is correct so l don't know why it doesn't work...

Thank you!

Joe278
  • 105
  • 1
  • 7

1 Answers1

0

I suggest to change the span as follows:

<span id="toTop" onclick="myFunction();"><i class="fa fa-angle-up" aria-hidden="true"></i></span>

Only add an event handler for onclick and call the following JavaScript function to get the effect:

function myFunction() {
    $('html, body').animate({scrollTop:0}, 'slow');
    return false;
}

In my example I am using jQuery, as it is easier to implement: Link to example

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Diego Avila
  • 700
  • 7
  • 24