1

I have a website with some news. I create a view that shows them and filter by category. When I use the filter, it reloads the page and goes at the top of the page. I want it doesn't move on the top of the page.

I added an anchor to the page, but I can't add it to the view redirect link. I tried implementing hook_view_form_alter() to add a custom submission handler, but it breaks the entire form and the news are not filtered.

I also looked at hook_views_query_alter(), but it doesn't seem it allow to do what I am trying to achieve.

Is there any way to do this?

5
  • There is something similar asked for drupal 7 search results, I believe it can be used for Drupal 8 as well drupal.stackexchange.com/questions/260697/… – GiorgosK Apr 24 '19 at 13:25
  • The problem with that script is that it scroll to the content every time I go on the page, I want to scroll only when the page is refreshed by the filters form – user93063 Apr 24 '19 at 13:52
  • With a little modification you can achieve what you want ;-) – GiorgosK Apr 24 '19 at 15:29
  • Yes it works now I just add a condition to check if I have query éléments in my URL – user93063 Apr 25 '19 at 5:55
  • I wrote up a simple solution below based on the D7 one. – GiorgosK Apr 25 '19 at 7:46
1

Here is a simple solution to scroll to top of the views results using jquery scrollTop

THEMENAME/js/views-scroll-top.js

(function ($, Drupal) {
  Drupal.behaviors.viewsScrollTop = {
    attach: function (context, settings) {
      //var scrollto = ".view-content"; // top of results
      var scrollto = ".view-filters"; // top of filters
      var url = window.location.href.split('?');
      if (url.length > 1 && $(scrollto).length) {
        $("html, body").animate({ scrollTop: $(scrollto).offset().top }, "slow");
      }
    }
  };
})(jQuery, Drupal);

THEMENAME/THEMENAME.libraries.yml

views-scroll-top:
  js:
    js/views-scroll-top.js: {}

THEMENAME/THEMENAME.theme

function THEMENAME_preprocess_page(&$variables) {
  // attach library only on specific view
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === "view.article.page_1") {
    $variables['#attached']['library'][] = 'THEMENAME/views-scroll-top';
  }
}

Change THEMENAME to your theme's name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy