Reputation: 3221
I have a function where variables are declared within that function and I need to make another function that will use those variables and will run when I click a button on a HTML doc, do I create a nested function and call that, if so how?
Upvotes: 0
Views: 1351
Reputation: 17757
JAVASCRIPT:
function MyFunction_outer(){
var local variable1=some_value;
var MyFunction_inner=function(some_value){
alert(some_value);
}
}
HTML:
//this is how call a function onclick.
<div onclick="MyFunction_outer" >CLICK_ME</div>//for outer function
<div onclick="MyFunction_inner" >CLICK_ME</div>//for inner function
This is how you call a function. You can also use addEventListener if you dont want to write inline code and pollute your HTML code.
Using addEventListener-:
document.getElementById('button_id').addEventListener("click",function({MyFunction_outer()},false)
OR
document.getElementById('button_id').addEventListener("click",function({MyFunction_inner()},false)
Upvotes: 0
Reputation: 780818
function outer(some_var) {
function inner() {
alert(some_var);
}
document.getElementById("my_button").onclick = inner;
// or
document.getElementById("my_button").addEventListener("click", inner);
}
Upvotes: 2