1

I'm trying to execute an event listener using eval()

["document.addEventListener('load', "].forEach(f => {
  eval(f + `function(){ console.log("test") })`)
})

The console never logs however. When I replace eval() with console.log, it shows that the string has correct syntax

["document.addEventListener('load', "].forEach(f => {
  console.log(f + 'function(){ console.log("test") })');
}) // logs 'document.addEventListener('load', function(){ console.log("test") })'

So if the syntax is correct, what's the problem?

When I remove 'function()' from the string and just directly fire 'console.log', it works.

["document.addEventListener('load', "].forEach(f => {
  eval(f + 'console.log("nice"))');
}) // this works
6
  • 1
    The event listener only fires on a load event which likely already happened Commented Apr 28, 2021 at 17:52
  • 1
    @Scrapper142 but when I remove 'function()' from the string and just directly fire 'console.log', like eval(f + 'console.log("nice"))', it works. If it were the window loading already happening, wouldn't it not work either way? Commented Apr 28, 2021 at 17:54
  • 1
    In the second example the string its evaluating ends up being 'document.addEventListener('load', console.log("nice"))', so since you are directly executing console.log("nice"), it executes it (thats when it prints), but then adds the event handler becomes undefined Commented Apr 28, 2021 at 17:59
  • 1
    Ah you're right. Is there an alternative to document.addEventListener('load") that I can use? I need to perform this function right at the start of the app. Commented Apr 28, 2021 at 18:13
  • 1
    Yes, the actual eval() content will be setting innerHTML values. I need to set innerHTML values right when the app starts, and then later when a slider is inputted (that's why I'm doing a forEach, the second string will be an eventListener for inputting an element.) Commented Apr 28, 2021 at 18:18

1 Answer 1

1

Moved here because longer answer

You could try a function that takes the code string, and runs it immediately if the page is loaded otherwise add an event listener

function runWhenLoaded(codeString) {
  if (document.readyState === 'complete') { // checks if it is loaded already
    eval(codeString);
  else {
    document.addEventListener('load', () => eval(codeString));
  }
}

Sign up to request clarification or add additional context in comments.

1 Comment

Then you can add another event listener for the slider

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.