Hello fellow developers,
Like you; I love to create and use plugins that you built, and they always come in handy so thank you.
But there is something that sometimes seems to not make them “not truly usable” is some scenarios. One of these scenarios that I almost always face is that the plugin code runs before the page renders an element with the target ID
So please keep in mind that, Bubble does not always render an element in the DOM when the page is loaded. So when you have a plugin that requires an element with an ID somewhere in a repeating group, popup, reusable element or vice-versa the plugin fails!
To fix this I use a mutation observer (if needed by the plugin). I first call on the code to run it and if the element is not there then I observe changes in the DOM till it appears. Then I disconnect.
Can I request all developers to pitch in and use this, please?
The code I usually use looks like this
if (document.getElementById(element_names)) {
//If it found do something run your code as you normally do
} else {
console.log('Warning! - Toolit Kit Input Formatter', 'The target element is not on the page. Plugin will wait till element appears');
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == 'attributes' && mutation.target.id == element_id_your_looking_for) {
//When its found do something. Run your code
//Disconnect
observer.disconnect();
}
});
});
//This config usually works best for Bubble
let observerConfig = {
childList: true,
subtree: true,
attributes: true
};
// Listen to all changes to body and child nodes
let targetNode = document.body;
observer.observe(targetNode, observerConfig);
}