From: Jérémy Fabre Date: Fri, 14 Oct 2016 10:36:39 +0000 (+0200) Subject: Scrollspy implementation X-Git-Url: https://git.parisson.com/?a=commitdiff_plain;h=8ea11d3b7ae1bfc5c481d510763403e221122f85;p=mezzo.git Scrollspy implementation --- diff --git a/app/static/src/js/modules/summary.js b/app/static/src/js/modules/summary.js index b46c6542..46459d5a 100644 --- a/app/static/src/js/modules/summary.js +++ b/app/static/src/js/modules/summary.js @@ -2,6 +2,7 @@ var Summary = function() { this.$summary = $('[data-summary]'); this.$content = $('[data-summary-content]'); + this.$links = []; // // Init @@ -24,9 +25,13 @@ Summary.prototype.init = function() { var $element = $(this), $template_clone = $template.clone(); + $template_clone.find('a').text($element.text()); $template_clone.find('a').attr('href', '#section-' + sectionCount); $template_clone.removeClass('hide'); + + that.$links.push($template_clone.find('a')); + that.$summary.append($template_clone); $element.attr('id', "section-" + sectionCount); @@ -38,6 +43,44 @@ Summary.prototype.init = function() { $template.remove(); + // Scrollspy + $(document).on("scroll", that.onScroll.bind(that)); + + } + +}; + +Summary.prototype.onScroll = function(e) { + + var scrollPos = $(document).scrollTop(), + that = this, + currentTitle, minDiff = 9999999999999; + + that.$links.forEach(function (elem) { + var currLink = elem; + var refElement = $(elem.attr("href")); + var diff = refElement.offset().top - scrollPos; + if(diff < minDiff && diff > 0) { + minDiff = diff; + currentTitle = refElement; + } + if (refElement.position().top <= scrollPos) { + that.$links.forEach(function (elem) { + elem.removeClass('active'); + }); + currLink.addClass("active"); + } + else{ + currLink.removeClass("active"); + } + }); + + that.$links.forEach(function (elem) { + elem.removeClass('active'); + }); + + if(currentTitle) { + $('[href="#' + currentTitle.attr('id') + '"]').addClass('active'); } };