There is a representation in which the filter by the title is opened, after entering the word, the presentation is reloaded via ajax, and my own handwritten accordion stops working, I know that there is a ready-made module. But it is fundamentally for me to learn how to hang scripts even after ajax triggers.

On the screen view: enter image description here

And this is my script that collapses / expands an element when clicking on the title

(function($) { Drupal.behaviors.a_module = { attach: function(context, settings) { $('.view-id-question_answer.view-display-id-page .views-field-title').click(function() { $(this).parents('.views-row').siblings().removeClass('active').find('.views-field-body').slideUp(200); if ($(this).parents('.views-row').hasClass('active')) { $(this).parents('.views-row').removeClass('active').find('.views-field-body').slideUp(200); } else { $(this).parents('.views-row').addClass('active').find('.views-field-body').slideDown(200); } }) } }; }(jQuery)); 

Now after rebooting via ajax, when clicked, the function works 2 times (expands and collapses the element)

I think this is due to the fact that attach: function (context, settings) runs everything inside of itself as if twice, for example, when sending a request to the server and upon receipt, if this is the case and I did not write nonsense, then tell me how to make the function worked as it should (one click expands, the next click collapses), and not repeatedly

  • Usually such things are solved through .toggle (); use jquery once. - And

1 answer 1

In some situations, Drupal.attachBehaviors() can be called several times, respectively, Drupal.behaviors.a_module.attach() hang several click handlers on the target element. In order for the bihavior to work only once, you can check whether the target element has a unique CSS class. If the target element does not have a class, then add a unique class to this element and execute code of bihivor, otherwise ignore the processing.

  ... attach: function(context, settings) { var cls = 'a_module_processed' , $target = $('.view-id-question_answer.view-display-id-page .views-field-title', context); if ($target.hasClass(cls)) { return; } $target.addClass(cls).click(function() { ...