Calling JavaScript function from String

While creating the jQuery plugin for DIV TEXT BOX: Create orkut style status update box, I had a requirement where in I had to call a JavaScript function whose name is specified as a string in some tag. For example, user is giving name of function in a text box and you have to call that function.

Calling simple JavaScript function is easy, just call it :)
e.g. someFunction() or someOtherFunction(‘text’, 101);

But what if you don’t know the name of function to be called and you know this only at runtime? Check following demo.

Demo


In above demo, click Call button. You can see an alert box with value ‘Happy New Year.!!’. Once you click the Call button, a function fnFooBar gets called. The name of the function and parameter is specified in first text box and the body of the function is in the text area.

Change the function parameter or add a new function in the textarea and call it from text box and then click Call button. You can see that the function gets called although it is not parsed by the browser.

Now how do we do this? Simple, we use eval() method of JavaScript to evaluate and register the javascriot elements dynamically.

Thus is you have a string whose value is the function name. You can call it by eval() function as follow:

var strFun = "someFunction";
var strParam = "this is the parameter";

//Create the function call from function name and parameter.
var funcCall = strFun + "('" + strParam + "');";

//Call the function
var ret = eval(funcCall);

You can use eval() function to register any kind of JavaScript code like loading a JavaScript file from using AJAX and then registering it with the browser. This way you can load your BIG BIG javascript files on fly by ajax and register it as an when required.

UPDATE:
It seems that there is a better way to do this without using eval method. Thanks @Jerome for the comment.

Use window[functionName](parameters) to call any function functionName. See below example:

var strFun = "someFunction";
var strParam = "this is the parameter";

//Create the function
var fn = window[strFun];

//Call the function
fn(strParam);


30 Comments

  • Matthew Holloway 4 March, 2009, 3:33

    How do you send parameters that aren’t strings to the function though? Lets say you’ve got FunctionNameString and Object … how would you call FunctionNameString(Object) ?

  • JS 19 September, 2009, 19:52

    What I found easier is:

    // convert string to a function reference (if it exists)
    fun = eval(strFun);
    // call it
    fun(param1, param2);

    This worked in IE6 and FF3.5 so I guess it works in others too.
    Using this method enables me to use objects as parameters.

  • Akshat Maheshwari 12 August, 2010, 18:30

    It helped me a lot…….
    Thanxs.. :)

  • Horoskop Skorpion 7 September, 2010, 5:35

    Good info

  • GenysLt 26 January, 2011, 4:28

    Thank You

  • anna 26 September, 2011, 12:57

    thx=) help me a lot ;)

  • teal 26 September, 2011, 15:26

    You should understand that using of ‘eval’ is not good enough practice. Happily all js functions are stored in huge ‘window’ object (if you use js inside browser, of course).
    So you can get direct pointer to your function by calling
    window[‘here_is_your_function_name_in_string’];
    Or you can even test if this function exists:
    window.hasOwnProperty(‘here_is_your_function_name_in_string’);

    Ok, complete sample is:
    var s = “my_function”;
    if (window.hasOwnProperty(s)) window[s](params);

  • jonas 4 October, 2011, 14:33

    Great!! Been looking desperately for this functionality!!!

  • jey 14 December, 2011, 11:22

    javascript eval() function

    name0,name1,name3 are javascript variables.
    jline0,jline1,jline2 are javascript arrays

    str=”{name : name0,data : jline0},{name : name1,data : jline1},{name : name2,data : jline2 }”;
    var ff=eval(str);

    document.ready(
    .
    .

    series :[ff]
    .
    .
    });

    I can’t pass ff value in series parameter. Please anyone help me. .

  • ssam 10 January, 2012, 21:33

    eval is bad, this is the worst way of executing a function.

    • Viral Patel 10 January, 2012, 22:10

      @Ssam – I agree with you. Using eval is not advisable. But in the given situation eval is only option, where one would like to call a function at runtime using just a name.

      • jerome 23 January, 2012, 22:58

        Correct me if I’m wrong, but this could also be a good solution, provided the only hint you’ve got on the function to execute is its name :
        http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call

        I tried this with success :
        window[functionName](param);

        screw eval !! :D

        • Viral Patel 24 January, 2012, 0:16

          Jerome, My bad :) I must agree I din’t know about this method. Thank you so much for getting this to my attention. I’ll update the tutorial right away and add this option as preferred solution.

  • Monkey 14 February, 2012, 19:27

    Also, it is not well interpreted in a “jQuery object” environnement:

    var myjQueryObject = function()
    {
     function oglop(arg)
     {
       alert(arg);
     }
    
     function init()
     {
       window['oglop']('gwok gwok!');
     }
    
     return {init: init, oglop: oglop};
    }();
    

    This won’t work until you create the function outside the myjQueryObject class.

  • Spanich 13 March, 2012, 14:53

    I was expecting fn to be executed under window object, so that context for the function will be window, but not the current object.
    So, I need not a “call”, but “apply” method like in the following post:
    http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

  • arun 29 May, 2012, 18:46

    function oglop(arg)
    {
    ———–Here I need call code behind function ———————
    is it possible
    }

  • Amit 1 June, 2012, 15:43

    function oglop(arg)

    {
    ———–Here I need call code behind function ———————
    is it possible
    };

  • Hitesh 1 June, 2012, 16:19

    jquery multi combobox selected first elements in display after remove option

  • roemly 6 July, 2012, 7:47

    thank u very much ^_^

  • Rahul Jawale 13 August, 2012, 19:11

    Thanks man. You are a savior!!! :)

  • hooom 23 August, 2012, 4:31

    eval is bad idea if you care security

  • rajesh 26 November, 2012, 12:55

    thanks a lot it helped so much

  • syam 27 February, 2013, 0:40

    It’s working good it helped a lot

  • Peter Drinnan 31 May, 2013, 19:01

    If you’re using jQuery you can try using isFunction.

    Here is an example:

        function sayhi() {
        alert(‘hi there’);
        }
    
        var funcCall= “sayhi”;
    
        if($.isFunction(funcCall)) {
        eval(funcCall);
        }
    
  • kamayani 12 June, 2013, 20:44

    very useful

  • anonymous 10 September, 2013, 20:10

    Thank God Someone has finally given me the information I needed in a way that I can understand. Other forums had parts of the code but not the complete coding which was confusing. Thanks a lot mate

  • SteeveC 22 January, 2014, 18:28

    Nice, thx you, i was looking for this solution since long time.
    Thx you very much

  • kv1dr 12 February, 2014, 12:35

    It works :D

  • LaurentM 13 May, 2014, 15:18

    It works very well :-) Thanks !

  • vrushali 15 October, 2014, 16:03

    GUD Thanks

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *