Background
I have a filtered view for the content type "Change Requests" that I built as a page, and as a block. The block is added to the user's home page and only shows that user's change requests. The filters div was always visible, but I wanted it to be collapsed and to have a button which expands the filters when the user wants to change it.
I added a button, some custom styling to show/hide the filters block, and a jQuery file that finds the button ID and adds an event listener to it. This worked successfully at first, but then I noticed that when you refresh the home page, sometimes the event listeners are not added to the block and it does not function at all. The view page on the other hand works seemingly every time.
This seems to work sometimes but not other times. For example, sometimes the home page loads and the functionality works, but other times it does not. If I refresh the page a few times, it will load at least once without the event listener added. This also happens when I click the home page link or on first time load, and not just when I am refreshing the page.
Setup
All three steps were used to alter or create files within my custom theme folder.
- Altered
views-exposed-form.html.twig
and added a button after the filters div:
<div class="form--inline clearfix filters">
{{ form }}
</div>
<button id="expand-filters" type="button" class="button" aria-pressed="false">filters</button>
- Added some styling in the CSS to hide/show filters:
.filters {
display: none;
}
.filters.visible {
display: block;
}
- Created a jQuery file that adds event listener to button to show/hide the filters div:
jQuery(document).ready(function($) {
// Expand Filter Button
$('#expand-filters').on('click', function() {
$(this).toggleClass('active');
$(this).attr('aria-pressed', $(this).attr('aria-pressed') === 'true' ? 'false' : 'true');
$('.filters').toggleClass('visible');
});
});
It seems to me that sometimes the files either don't execute after the document loads, or they execute before elements are loaded and thus fail to add the event listeners. That is my guess, as I don't fully understand why this isn't working in the block but is working in the view.
Question
What is the right way to add this functionality so that it works every time, and not intermittently? I am open to solutions which add modules, but my preferred method is to add this functionality within the theme so that it works only by loading my custom theme into pages.
Additional Info
This site is using Drupal 10 so I am trying to use any and all conventions that apply to Drupal 10.