Override views AJAX "Scroll to top" JavaScript?

Created on 27 July 2023, over 1 year ago
Updated 31 July 2023, over 1 year ago

I have a D10 site that is using a view that has AJAX turned on along with pagination. The default behavior is that if you are at the bottom of the result set and you click to go to another page using the pagination buttons and AJAX fires, you automatically get scrolled to the top of the page. This works, however, it is not working correctly for my site, because my site also has a fixed header, so the header ends up overlapping the top of the view after it scrolls to the "top of the page". I came across an article here:

https://timonweb.com/archive/fixing-views-scroll-to-top-when-you-have-a-...

This addresses this exact issue, but the problem is that the article is very old and using old ways of doing things in Drupal. Can anyone steer me in the right direction on fixing this same issue but doing it in the d10 way?

THANKS!

πŸ’¬ Support request
Status

Closed: won't fix

Version

10.1 ✨

Component
AjaxΒ  β†’

Last updated about 18 hours ago

Created by

πŸ‡ΊπŸ‡ΈUnited States socalerich

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @socalerich
  • πŸ‡·πŸ‡ΊRussia kostyashupenko Omsk

    Normal way is to extend library in `themename.info.yml`:

    libraries-extend:
      views/views.ajax:
        - my_theme/views.ajax
    

    Then declare new drupal library in `themename.libraries.yml`

    views.ajax:
      js:
        path/to/your/js/file/override.js: {}
    

    and then in js file you can override Drupal.AjaxCommands.prototype.viewsScrollTop = function (ajax, response) {

    https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/views...

    Here you can do whatever you need

  • Status changed to Closed: won't fix over 1 year ago
  • πŸ‡ΊπŸ‡ΈUnited States socalerich

    Just in case anyone else ends up having this issue, I followed the steps above and this was my JavaScript that ended up working as far as the override goes. One note is that the "header_height" variable is dependent on what your projects actual header height is, so you may need to adjust that.

    (function ($, Drupal) {
      Drupal.AjaxCommands.prototype.scrollTop = function (ajax, response) {
        var offset = $(response.selector).offset();
        var scrollTarget = response.selector;
    
        while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
          scrollTarget = $(scrollTarget).parent();
        }
    
        var header_height = 200;
    
        if (offset.top - header_height < $(scrollTarget).scrollTop()) {
          $(scrollTarget).animate({ scrollTop: offset.top - header_height }, 500);
        }
      };
    })(jQuery, Drupal);
    
Production build 0.71.5 2024