0

I want to be able to run a function that is passed by name from a data attribute on the HTML side. I've tried the following below.

HTML:

<div class="generic-select" data-help-on-shown="genericFunction" >          
</div>

Javascript:

function genericFunction() {
    console.log("generic function called");
}

Other Javascript (separate file):

//stepEl is correct divider from above
var genFunction = typeof (stepEl.data("helpOnShown")) === "undefined"
                    ? null
                    : stepEl.data("helpOnShown");

//this prints "genericFunction" as expected
console.log("genFunction = " + genFunction);

if (genFunction) {
    genFunction(); //gives error!
}

However, this gives me an error. Is there a way to call a function by a string name?

1 Answers1

0

If the function is "global", it exists as a property of window:

window[functionname]()
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202