Tim
Tim

Reputation: 3221

Nesting functions in JavaScript and variable scope?

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

Answers (2)

HIRA THAKUR
HIRA THAKUR

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

Barmar
Barmar

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

Related Questions