Pages

Dynamically assign a function to event in javascript

In javascript, using code we can assign function to the events of the elements.

In general, we can assign the function name to the event name directly, Please see the below example.

var element = document.getElementById("testElement");
element.onclick = DynamicFunction;

function DynamicFunction()
{
 alert("sample function");
}


Consider a scenario where you have to assign a function with parameters. we cannot do in the below mentioned way. this will throw a script error.

var element = document.getElementById("testElement");
element.onclick = DynamicFunctionWithParameters(x,y);

function DynamicFunctionWithParameters(param1, param2)
{
 alert("sample function");
}


we have to go with a round about way to achieve the same, see the below example.

var element = document.getElementById("testElement");
element.onclick = function(x,y){DynamicFunctionWithParameters(x,y);};

function DynamicFunctionWithParameters(param1, param2)
{
 alert("sample function");
}


I think you know, we can even directly write the function instead writing it separately and assigning it to the event later. the below example explains this. while mentioning this way we cannot have the function name, and also the same function cannot not be reused.

var element = document.getElementById("testElement");
element.onclick = function(param1, param2)
{
 alert("sample function");
};

No comments:

Post a Comment