diff --git a/js/modal.js b/js/modal.js index c757ef2..72bdc79 100644 --- a/js/modal.js +++ b/js/modal.js @@ -303,6 +303,7 @@ if ($('#modal-content').hasClass('ctools-modal-loading')) { $('#modal-content').removeClass('ctools-modal-loading'); + modalContentResize(); } else { // If the modal was already shown, and we are simply replacing its @@ -311,6 +312,43 @@ // button by the show() function called above.) $('#modal-content :focusable:first').focus(); } + + // Trigger a window resize after a delay to ensure that the modal is + // centered properly. + // See https://www.drupal.org/node/1803104 + Drupal.CTools.Modal.center_modal(); + + } + + /** + * Ensure modal is centered. + */ + Drupal.CTools.Modal.center_modal = function() { + // If the modal doesn't exist, bail. + var $modal_content = $('#modalContent'); + if ($modal_content.length === 0) { + return; + } + // Get the middle of the window. + var windowCenter = $(window).width() / 2; + // Get left, width, and center of the modal. + var modalLeft = $modal_content.offset().left; + var modalWidth = $modal_content.width(); + var modalCenter = modalLeft + modalWidth / 2; + // Check to see how far off the modal and window middles are. + var diff = windowCenter - modalCenter; + // Consider the modal not centered if it has a width less than 10, or if + // its left edge is not at zero and the difference between the window + // center and the modal center is greater than |1| (we allow a difference + // of 1 positive and negative in case division result a float). + if (modalWidth < 10 || (modalLeft > 0 && (diff > 1 || diff < -1))) { + // Modal is not centered. Trigger resize to force modal to center and + // wait 10 ms before retrying. + $(window).trigger('resize').delay(10).queue(function(){ + $(this).dequeue(); + Drupal.CTools.Modal.center_modal(); + }); + } } /** @@ -633,7 +671,8 @@ // Apply the changes $('#modalBackdrop').css('height', docHeight + 'px').css('width', docWidth + 'px').show(); - modalContent.css('top', mdcTop + 'px').css('left', mdcLeft + 'px').show(); + var topPx = mdcTop < 0 ? 0 : mdcTop; + modalContent.css('top', topPx + 'px').css('left', mdcLeft + 'px').show(); }; $(window).bind('resize', modalContentResize); };