]> git.parisson.com Git - mezzo.git/commitdiff
Scrollspy implementation
authorJérémy Fabre <Jeremy@iMac-de-Jeremy.local>
Fri, 14 Oct 2016 10:36:39 +0000 (12:36 +0200)
committerJérémy Fabre <Jeremy@iMac-de-Jeremy.local>
Fri, 14 Oct 2016 10:36:39 +0000 (12:36 +0200)
app/static/src/js/modules/summary.js

index b46c6542da6ab4066b3c57ac019c69507e6aba83..46459d5a90f0b8404b19311b6ae9365b1701ad00 100644 (file)
@@ -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');
     }
 
 };