DOMContentLoaded not work on symbol

Hello everyone!

Im trying to add the DOMContentLoaded event into the main function of my symbol custom javascript code but that event is never executed.

This is a dummy example:

The ‘Hello builder!’ is never showed in console logs of the symbol preview.

I tryed too with ‘window.onload’ and ‘window.addEventListener(“load”, function())’

Thanks 4 reading!

hey @tarica could you provide a bit more context, what are you looking to achieve by using the DOMContentLoaded event? There might be other or better ways to achieve your end goal

@TimG thank you for your answer.

I wanna manipulate some dom elements by js. For example, in my symbol i have a custom html block and inside of that i have a svg shape. So i wanna change the color of that shape dynamically by the user input.

But in my symbol i getting this warning and code is not working.

I think the problem is because the code is executed before the element exists.

@tarica I see, if these changes are based on user interactions, then you shouldn’t necessarily have to wait for page load. You should be able to add custom code in either the Custom JS + CSS window
Screen Shot 2022-03-08 at 3.22.27 PM

Or by adding actions to the elements themselves

I looked at your space in Builder, and for example on your Location Component symbol, you should be able to just add a click event to each country button, and when a user clicks that country you could add that country to state, say state.currentCountry = state.countriesItem.text for example
Screen Shot 2022-03-08 at 3.28.24 PM

Then, on each of the locations you wish to manipulate the background color you can add a element binding to say something along the lines of if
state.currentCountry == 'xyzCountry' ? state.selectedColor : state.unselectedColor
Screen Shot 2022-03-08 at 3.33.09 PM

Or whatever makes sense for your set up…Try that out and see if you are able to figure something out! Let me know if I am missing something or if I can help answer any other questions!

I got your point, thank you!
So it is not possible to use the javascript event listener?

Hey @tarica it still should! I was just trying to make the point that for the majority of use cases within Builder, it might be more reliable and straight forward to not rely on window load events :slight_smile:

That being said, it still should work in a custom code block, or within the JS window, I recommend checking out this article: Why is my custom code with script tags not loading on my Builder pages?

See if any of those recommendations help? Let me know!

But

I really appreciate your help.

Isn’t working for me, the window load events never run. I tried in the custom js window and the custom code. Also, in the custom code i cant access to state object.

So i think the avoid loading events approach is the good one.

1 Like