Difference Between Current Position And Scrolled Position With JQuery
Solution 1:
You basically need to have some kind of a factor to multiply its value by some certain vertical value, i.e: having 6 links with around 3000px document height means you need to make it so that the more distance between current position and target position is, the more this factor will be to have longer animation period for far distance.
Like in this JS Fiddle
My solution was if you're on "Section TWO" with the link dot (2) activated, if you click on (3) targeting "Section THREE", the animation duration will be Math.abs(2 - 3) * 250
so the scrolling will last for 250ms
.
While if you're on "Section TWO" (2) and clicked on link (5) to scroll the page to "Section FIVE", the formula will be Math.abs(2 - 5) * 250
which results a 750ms
animation duration.
This solution automated and much less code, unlike if-else if
statements which you need to add new condition for every new section. even if your sections varies a lot in height you can get each section height with javascript and compose your own similar formula.
JS:
// initializing
var prevLinkId = 0,
body = $('html, body');
/* some code */
// get the numeric part of the linkId of the anchor that just been clicked
// remove the active .highlight class name from all links
// and assign it to the just clicked link
linkId = $(this).attr('id');
linkId = linkId.replace('lnk', '');
links.removeClass('highlight');
$(links[linkId]).addClass('highlight');
// compute the absolute differet between the previous link value and the new one
// to have a variable factor when multiplied by the step "here 250ms" we get
// longer durations for larger distances, then we perform the scrolling
// below is the part responsible for making flexible durations
diff = Math.abs(linkId - prevLinkId);
timeDelay = diff * 250;
distance = index * secHeight;
body.animate({scrollTop: distance} , timeDelay);
//finally set the just clicked link as previous link for future calculations
prevLinkId = linkId;
Post a Comment for "Difference Between Current Position And Scrolled Position With JQuery"