0

HTML- referencing JS function inside another function issue

So I had a function that accessed the DOM too early, resulting in an error to find HTML elements. so I put my script inside another function: window.onload = function() { function myFunc() { // blah blah blah } } This works fine, but I need a button onclick to invoke the inner function. Does anyone have any easy workarounds for this issue?

21st Jun 2018, 3:14 PM
privrax.
privrax. - avatar
3 Answers
+ 11
A function accesses the DOM only when called. The contents of functions are never scanned so there's no problem defining it outside, only calling it before DOM loads... In Worst-Case scenario, do: onload = function() { window.myFunc = function myFunc() { // blah blah blah }; };
21st Jun 2018, 3:27 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 1
Yea, I realized the button couldn’t be clicked by the user if the DOM hadn’t loaded, so I got rid of the window.onclick = function() {} part and it works fine. The only other problem I’m having is that the function adds elements to the script, and according to the added element’s ids/classes, they are supposed to be rendered by CSS which isnt happening. Would I have to manually add the style param every time the button is clicked (invoking the function that adds elements)?
21st Jun 2018, 3:30 PM
privrax.
privrax. - avatar
0
Attaching 'onclick' attribute is not really a desired way. Grab the button with JS and add event listener to it like this: const myButton = document.querySelector('#buttonID'); myButton.addEventListener('click', () => { // your code goes here }); and then you can wrap your code in window.onload
21st Jun 2018, 3:27 PM
damyco
damyco - avatar