Why does js click function run multiple times? 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?
Most importantly you have to use the JQuery selector context. Otherwise you run the entire DOM through your js code anytime when Drupal behaviors passes you only context to process.

If your function still runs multiple times, add once() with a unique identifier:

$('input.myCustom', context).once('mySecondBehavior').each(function () {


Don't forget to add the library core/jquery.once to mytheme.libraries.yml, see https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview