0

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?

5
  • 4
    Good place to start: stackoverflow.com/questions/111102/… Commented Jul 16, 2013 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. Commented Jul 16, 2013 at 21:32
  • Type all your variables as window.variableName, and you can use them anywhere. It's great! Commented Jul 16, 2013 at 21:33
  • @Barmar It's a good article but I still don't know how to call it with an 'onclick'? Commented Jul 16, 2013 at 21:36
  • @Barmar:dont try to kill him.haha Commented Jul 16, 2013 at 21:40

2 Answers 2

2
function outer(some_var) {
  function inner() {
    alert(some_var);
  }
  document.getElementById("my_button").onclick = inner;
  // or
  document.getElementById("my_button").addEventListener("click", inner);
}
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

He wants to put the inner function in the onclick, not the outer function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.