1

I am trying to pass a function var into a click event. See the code below.Appreciate.

function coolfunction(){
           var cool="hello";
  }

$('#good').on('click',function(){
             alert(cool);//how can i pass the function var here

  });
I am trying to pass a
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="good">click</div>

3
  • What are you trying to do? Local variables are only visible inside the function they're declared in. If you want a variable accessible outside, use a global variable instead. Commented May 8, 2015 at 18:32
  • can I create global variable inside the function? Commented May 8, 2015 at 18:34
  • Yes. If you assign a variable without using a var declaration, it assigns the global variable. Commented May 8, 2015 at 18:37

2 Answers 2

1
var cool = '';

function coolfunction(){
     cool="hello";
}

$('#good').on('click',function(){
      coolfunction();
      alert(cool);//this will print "hello"
});
Sign up to request clarification or add additional context in comments.

3 Comments

This won't alert anything.
What if I cannot put the function inside the click, do I have another option?
@conan what do you mean?
0

You can pass the name of the function

$('#good').on('click', coolfunction);

then put the alert in coolfunction

function coolfunction(){
       var cool="hello";
       alert(cool);
}

If you don't want the alert in coolfunction, then return cool in coolfunction and use the return value.

function coolfunction(){
       var cool="hello";
       return cool;
}

$('#good').on('click', function() {
    var cool = coolfunction();
    alert(cool);
});

Comments

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.