Been there myself recently as a person with vanilla JS backgrond. The question/hint is in the way you execute your JS code. Did you just drop a file in assets folder with the content as you described?
Then it executes before button exists. You may notice that when you open Dash app it goes into loading state first. So in your JS script you need to execute the code after the page has been loaded. You can use events for this or write some code with setInterval function to wait for the button to appear.
Using setInterval, the JS script works fine, (I just drop the js file in assets) . Example:
console.log('Begin...');
let interval = setInterval(function () {
if (document.readyState === 'complete') {
clearInterval(interval);
myMain();
}
}, 100);
function myMain() {
let a = document.querySelector('button#btn');
console.log("Document loaded....", a);
a.style.backgroundColor = "blue";
}
For post completeness, can someone post a “use events” code sample or any way in dash to define that the JS script in assets is executed after the page is loaded?
in my mind, you are using events in your code - ready state. A different approach is to query the element and check the result for null.
Notice also that Dash can recreate your button. So, if you are going to use a later, it may be invalid. As far as I remember, if button is affected by a callback, then it will be recreated.