@Lawrence,
You'd need to provide more code/details about your Widget and where the above script is running to get detailed answers.
However, all Widget/Section HTML is rendered asynchronously on the client-side when in the Page Builder UI in the Administration application.
This means any JavaScript that executes expecting the Page HTML to be available when the Page loads, will not work and could be subject to weird race conditions.
Instead you need to either accept the fact that some JavaScript will not work correctly in the Page Builder (but will work fine in 'Preview' mode), or create event hooks that Widget code can call when it's rendered in the DOM.
Here's the lifecycle of a Page Builder Page:
- Page is rendered via ASP.NET Core (without any Page Builder component HTML)
- Browser receives HTML and executes Xperience Page Builder JS
- Xperience Page Builder JS makes XHR requests back to ASP.NET Core app for Page Builder component HTML (this happens in parallel for all Editable Areas defined on a Page)
- HTML is returned for Sections/Widgets and the Editable Area markers are replaced with this HTML
You will need to have 2 patterns for executing JavaScript:
- When executing in 'Page Builder' mode, the Widget/Section View should execute the JS when the Widget/Section is added to the Page
- When executing in 'Preview' or 'Live' mode, the Page executes the JS when the DOM is loaded