0

I have a button and I have function which should execute on click.

example:

<button id="button1">bla bla</button>
<script>
var justFunctionName = "function1";
var function1 = function()
{
alert("!");
}
$("#button1").click(justFunctionName);
</script>
asked Jan 8, 2014 at 16:20
3
  • 1
    stackoverflow.com/questions/496961/… Commented Jan 8, 2014 at 16:21
  • Why not just call function1 directly? Why are you going through the step of using a variable name for it? Commented Jan 8, 2014 at 16:22
  • in real code I declarate this function in an attribute. Commented Jan 9, 2014 at 6:54

3 Answers 3

2

HTML

<button id="button1">bla bla</button>


jQuery

var justFunctionName = "function1";
function function1()
{
 alert("!");
}
$("#button1").on("click", window[justFunctionName]);


See working jsFiddle demo

answered Jan 8, 2014 at 16:30
Sign up to request clarification or add additional context in comments.

Comments

-1
$("#button1").click(justFunctionName);

should be

$("#button1").click(function1);
answered Jan 8, 2014 at 16:22

Comments

-1
var justFunctionName = "function1";

This is assigning the string function1 to the variable justFunctionName.

If you were to do: console.log('justFunctionName'); you would end up with the following result:

>function1

Therefore this variable assignment is completely irrelevant for what you are hoping to achieve. Instead of just assigning a variable to a function you are assigning a variable to a variable which is assigned to a function.


Now take a look at what you are doing here:

var function1 = function () {
 alert("!");
};

This is assigning a variable function1 to the function doing the alert. In this instance, think of the variable as a reference to the function. In order to have the button trigger the alert, you need to call the reference to the function (in this case function1):

$("#button1").click(function1);
answered Jan 8, 2014 at 16:36

1 Comment

He wants to be able to call a function only with a name, the answer of Code Maverick seems to do the tricks. I can see it comming handy if, for exemple, you need to call a certain function depending of an attribute, for exemple ValidatePhone() or ValidateEmail() depending of the type of an object instead of calling Validate() and having a switch case that determine wich function to call.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.