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?
Asked
Active
Viewed 1,350 times
0
-
4Good place to start: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Barmar Jul 16 '13 at 21:29
-
you can bind to the button from within the outer function, or poke the variables through to globals and call them directly from html attribs. – dandavis Jul 16 '13 at 21:32
-
Type all your variables as `window.variableName`, and you can use them anywhere. It's great! – adeneo Jul 16 '13 at 21:33
-
@Barmar It's a good article but I still don't know how to call it with an 'onclick'? – Tim Jul 16 '13 at 21:36
-
@Barmar:dont try to kill him.haha – HIRA THAKUR Jul 16 '13 at 21:40
2 Answers
2
function outer(some_var) {
function inner() {
alert(some_var);
}
document.getElementById("my_button").onclick = inner;
// or
document.getElementById("my_button").addEventListener("click", inner);
}

Barmar
- 741,623
- 53
- 500
- 612
0
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)

HIRA THAKUR
- 17,189
- 14
- 56
- 87
-
He wants to put the inner function in the `onclick`, not the outer function. – Barmar Jul 16 '13 at 21:41