diff --git a/js/paragraphs.admin.js b/js/paragraphs.admin.js index 7f064d3..204366f 100644 --- a/js/paragraphs.admin.js +++ b/js/paragraphs.admin.js @@ -80,31 +80,31 @@ * In order to have a persistent position when switching tabs, * we add a class to the first paragraph visible in the viewport. */ - var getFirstVisibleParagraph = function () { - var scrollTop = $(window).scrollTop(); - var windowHeight = $(window).height(); + var getFirstVisibleParagraph = function (extraOffset) { + var $allParagraphs = $('.node-form .draggable'); + var $window = $(window); + var bottomOfScreen = $window.scrollTop() + $window.height() - extraOffset; + var topOfScreen = $window.scrollTop() + extraOffset; var firstParagraph = false; - // Check and add class to the first paragraph. - $(".node-form .draggable").each( function() { - var offset = $(this).offset(); - if (scrollTop <= offset.top && ($(this).height() + offset.top) < (scrollTop + windowHeight) && firstParagraph === false) { - $(this).addClass('first-paragraph'); + $allParagraphs.filter(function() { + var $this = $(this); + var topOfElement = $this.offset().top + extraOffset; + var bottomOfElement = $this.offset().top + $this.outerHeight(); + + // Add the class only to the first paragraph in the viewport. + if ((bottomOfScreen > topOfElement) && (topOfScreen < bottomOfElement) && firstParagraph === false) { + $this.addClass('first-paragraph'); firstParagraph = true; } - else { - $(this).removeClass('first-paragraph'); - firstParagraph = false; - } }); }; - /** - * For body tag, adds tabs for selecting how the content will be displayed. - * - * @type {Drupal~behavior} - */ + * For body tag, adds tabs for selecting how the content will be displayed. + * + * @type {Drupal~behavior} + */ Drupal.behaviors.bodyTabs = { attach: function (context) { var $topLevelParWidgets = $('.paragraphs-tabs-wrapper', context).filter(function() { @@ -118,18 +118,22 @@ // Create click event. $parTabs.find('a').click(function(e) { - getFirstVisibleParagraph(); + var toolbarHeight = $('.toolbar-tray-horizontal').outerHeight() ? $('.toolbar-tray-horizontal').outerHeight() : 0; + var extraOffset = $('#toolbar-bar').outerHeight() + toolbarHeight + $('.paragraphs-tabs').outerHeight(); + getFirstVisibleParagraph(extraOffset); e.preventDefault(); switchActiveClass($parTabs, $(this), $parWidget); - // Scroll to the first paragraph that was in the viewport - // before we clicked the other tab. - $('html, body').animate({ - scrollTop: parseInt($('.first-paragraph').offset().top) - }, 500); - // Reset the first paragraph class. - $('.first-paragraph').removeClass('first-paragraph'); + // Scroll to the first paragraph that was in the viewport vb. + if ($('.first-paragraph').length) { + $('html, body').animate({ + scrollTop: parseInt($('.first-paragraph').offset().top - extraOffset) + }, 500); + + // Reset the first paragraph class. + $('.first-paragraph').removeClass('first-paragraph'); + } }); });