Overriding Drupal JS function on the fly

Sometimes it is necessary that we solve some JS issues without making new deployment in production. Following example overrides the viewScrollTop JS function (originates from views module). The following code has to be added in AddToHead module of Drupal in the page-bottom section.

<script>
(function(Drupal, $) {
    Drupal.ajax.prototype.commands.viewsScrollTop = function (ajax, response, status) {
 // Scroll to the top of the view. This will allow users
 // to browse newly loaded content after e.g. clicking a pager
 // link.
 var offset = $(response.selector).offset();
 // We can't guarantee that the scrollable object should be
 // the body, as the view could be embedded in something
 // more complex such as a modal popup. Recurse up the DOM
 // and scroll the first element that has a non-zero top.
 var scrollTarget = response.selector;
 while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
   scrollTarget = $(scrollTarget).parent();
 }
 // Only scroll upward
 if (offset && (offset.top - 10 < $(scrollTarget).scrollTop())) {
   $(scrollTarget).animate({scrollTop: (offset.top - 10)}, 500);
 }
};
})(Drupal, jQuery);
</script>

Comments

Popular posts from this blog

Programatically create layout builder section in Drupal

Code quality analysis of Drupal. Can I use Sonar?

Set up Drupal7 to Drupal8 migration in simple steps (using Drush)