scrollSpy - offset calculation
Created by: davidgengenbach
I had an issue with the offset calculation of the items within a scrollspy element.
In the refresh function (which I had to use to recalculate the offsets) there is a calculation issue!
The offset is calculated with
$href.position().top
If the $scrollElement is already scrolled the offsets can be negative (like -200). You have to add the scrollTop() of the $scrollElement to it!
Sorry for my bad english!
refresh: function() {
var self = this,
$targets;
// added
var scrollTop = self.$scrollElement.scrollTop();
this.offsets = $([]);
this.targets = $([]);
$targets = this.$body.find(this.selector).map(function() {
var $el = $(this),
href = $el.data('target') || $el.attr('href'),
$href = /^#\w/.test(href) && $(href);
return ($href && $href.length && [
[$href.position().top, href]
]) || null;
}).sort(function(a, b) {
return a[0] - b[0];
}).each(function() {
self.offsets.push(this[0] + scrollTop); // added + scrollTop
self.targets.push(this[1]);
});
},