Skip to content

JavaScript call function by name | Code

  • by

Use the window object Method to call the function by name in JavaScript. it’s convenient to store function names in the string to use those strings to call the actual functions.

window[functionName](parameters)

The eval() method is an old method to call a JavaScript function

JavaScript call function by name

Simple example code change color or text onclick. In the string function pass parameter red to change the color of the h3 text on the click button.

<!DOCTYPE html>
<html>
<body>

  <h3 class="foo"> You called the function.</h3>

  <button onclick="evaluateFunction()"> Click Here</button>

  <script>

    function tColor(color) {
      document.querySelector('.foo').style = `color: ${color}`;
    }

    function evaluateFunction() {
      stringFunction = "tColor";
      param = 'red';
      window[stringFunction](param);
    }
  </script>
</body>
</html>

Output:

JavaScript call function by name

How to execute a JavaScript function when I have its name as a string?

Answer: You just need to convert your string to a pointer by window[<method name>]. example:

var function_name = "string";
function_name = window[function_name];

Source: https://stackoverflow.com/questions/359788/

Do comment if you have any doubts or suggestions on this js function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *