Javascript Snippet Widget does not run - inconsistent behavior

0
The Javascript Snippet widget does not consistently run. We have a page that sets up a click event on a button using the widget like so: function onClick() { logger.info('Clicked'); } function setupClickEvent(node) { node.addEventListener("click", onClick); } function checkForButton() { var interval = setInterval(function() { var selectButton = document.body.querySelector(buttonClassName); if (selectButton) { setupClickEvent(selectButton); clearInterval(interval); } }, 100) } checkForButton(); When navigating to and from this page, sometimes the event listener is added to the button and other times it isn’t. The behavior also varies across servers – I have yet to view this inconsistency on a local server. I’ve also tried implementing the event handler using jQuery and MutationObserver(s). Both of these implementations had consistency issues as well. I decided to go with the above solution because I figured it would be the MOST consistent since it only relies on the widget executing the js.
asked
2 answers
0

a few questions I have. where is buttonClassName defined? typically you would do document.getElementByClassName(‘btn’) where ‘btn’ is the actual class name but this is better to use getElementById instead so you don’t have an issue of retrieving the wrong button because if theirs several items with the same class name it will retrieve whichever one it finds first which is also why you might be getting some inconsistency.

if you did querySelector, this is best used to just retrive an element such as ‘button’

answered
0

You would be better looking at building a custom widget in JavaScript. You could then hook into the lifecycle events to correctly add and remove your event handlers when the widget is rendered or destroyed.

There is some documentation on how this all works. https://docs.mendix.com/howto7/widget-development/

answered