-1

I have the below jquery code to move a multiselect field and a button above the table.

jQuery(document).ready(function($){
  $('#views-form-resources-block-1 .form-item-ka-types').insertBefore($('#views-form-myblock-block-1 table'));
  $('#views-form-resources-block-1 #edit-actions--2').insertAfter($('#views-form-myblock-block-1 .form-item-ka-types'));
});

In this code I am moving the ka-types field above myblock view. Pictorial representation as below:

enter image description here

This code works fine when I load the page at first. But when I refresh the page, the multiselect comes down and shows messed up. again when I refresh the page it works fine. not sure what the problem is. Any help on how this can be fixed?

6
  • 3
    The Javascript is not written in a way that Drupal will attach it when the dom changes, so when a form rebuilds, this will be lost. It's probably easier to override this Views template to move a filter vs force it with jquery.
    – Kevin
    Jul 18 at 0:04
  • 2
    Otherwise review the Drupal docs on Drupal Behaviors.
    – Kevin
    Jul 18 at 0:14
  • I would also recommend doing this with yourjavas view's template. JavaScript changes like this will cause the page contents to shift which is not a nice UX. This could even negatively affect your SEO as a page's Cumulative Layout Shift (CLS) score is a factor.
    – sonfd
    Jul 18 at 11:35
  • Could you precise please, what the first refreshing means? A form submit? So maybe the DOM looks a little different after submitting. Jul 19 at 10:48
  • You can also check if web tools console shows any JS error, so your JS is never executed after submitting the form (first refresh) Jul 19 at 10:50
0

The below is my solution for this:

(function($, Drupal) {
  Drupal.behaviors.searchResults = {
    attach: function() {
      $('#views-form-resources-block-1 .form-item-ka-types')
        .insertBefore($('#views-form-myblock-block-1 table'));
      $('#views-form-resources-block-1 #edit-actions--2')
        .insertAfter($('#views-form-myblock-block-1 .form-item-ka-types'));
    }
  };
}(jQuery, Drupal));

@Kevin is correct. When the form rebuilds the DOM changes are lost. Better understanding of Drupal behaviors link has great explanation and examples of Drupal Behavior.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.