Javascript action is not working unless I click twice on the button

1
I am trying to add/remove a class to a specific element in template grid by using a Nanoflow that is calling a Javascript action. I know I might be able to do that using an associated entity but I want to avoid that.   The Javascript I wrote works but it is a bit buggy. It only works after clicking twice on the element.   Here’s the javascript I wrote:   // This file was generated by Mendix Studio Pro. // // WARNING: Only the following code will be retained when actions are regenerated: // - the import list // - the code between BEGIN USER CODE and END USER CODE // - the code between BEGIN EXTRA CODE and END EXTRA CODE // Other code you write will be lost the next time you deploy the project. import "mx-global"; import { Big } from "big.js";   // BEGIN EXTRA CODE // END EXTRA CODE   /** * @returns {Promise.<void>} */ export async function JavaScript_expandCard() { // BEGIN USER CODE   function toggleItem(elem) { for (var i = 0; i < elem.length; i++) { elem[i].addEventListener("click", function(e) { var current = this; for (var i = 0; i < elem.length; i++) { if (current != elem[i]) { elem[i].classList.remove('show'); } else if (current.classList.contains('show') === true) { current.classList.remove('show'); } else { current.classList.add('show') } } e.preventDefault(); }); }; }   toggleItem(document.querySelectorAll('.expandCardBtn'));   // END USER CODE }
asked
2 answers
2

On the first click you add the event listener, on the second the show class is toggled. If you're already executing a nanoflow, forget about the event listener. Also, have a look at classList.toggle()

answered
0

Our team was able to figure it out. The nanoflow is being called when the page is loaded instead of when the element is clicked!

answered