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.


Facebook  Twitter      Stumbleupon  Delicious
  

3 Comments on “Calling JavaScript function from String”

  • Matthew Holloway wrote on 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 wrote on 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 wrote on 12 August, 2010, 18:30

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

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.