I'm creating some accordion functionality for fields and paragraphs using a combination of twig templates and a custom JavaScript file.
Everything prints as expected and the basic accordion functionality works; however, the click function script is running multiple times, causing an "expand-collapse-expand-collapse..." behavior. See image:
Here is the script file:
(function($, Drupal) {
/* Add span to wysiwyg button classes for alignment
------------------------------------ */
Drupal.behaviors.accordionFaqFunction = {
attach: function (context, settings) {
$('.toggle').click(function(e) {
e.preventDefault();
var $this = $(this);
if ($this.next().hasClass('show')) {
$this.next().removeClass('show');
$this.next().slideUp(350);
console.log("hiding");
} else {
$this.parent().parent().find('li .inner').removeClass('show');
$this.parent().parent().find('li .inner').slideUp(350);
console.log("showing");
$this.next().toggleClass('show');
$this.next().slideToggle(350);
}
});
}
};
})(jQuery, Drupal);
Why is the script running multiple times?
Drupal.behaviors.attach
is executing multiple times, and you’re not making use ofonce
to ensure the event handlers are only bound once