You can, yes. Are you another question to which the answer is almost certainly โnoโ (in terms of line execution, in terms of the alternative shown below, this is sometimes useful).
The way you evaluate this piece of code (what you have is not just a function name, due to () ) is to use the scary eval :
eval(fn);
Almost always a better option than using eval . (See below.)
eval example:
$("#example").on("click", function() { var fn = $("#example").attr("data-function-name"); eval(fn); }); function showAllElements() { alert("showAllElements was called"); }
<button type="button" id="example" data-function-name="showAllElements()">Click Me</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
One of the best options is to save function references as object properties, and then use notes in brackets to get a function reference based on the function name:
Example:
var functions = { showAllElements: function() { alert("showAllElements was called"); } }; $("#example").on("click", function() { var fn = $("#example").attr("data-function-name"); functions[fn](); });
<button type="button" id="example" data-function-name="showAllElements">Click Me</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Please note that there I just save the function name, not arbitrary code.
Update : see canon answer for a clever way to handle if you have your own functions nested inside an object, for example. mumble.foo.doSomething using reduce . ( reduce is an ES5 function, but it is multicompleted.)
Note: if you are not doing something more than just data-* value of the data-* attribute, do not use data , use attr . data initializes the data cache for an element, reads in all data-* attributes for that element, and copies them into the cache. If you do not use it, there is no reason for this. The idea of โโusing data to access data-* attributes is a common misconception.
source share