1

I want to assign global variable value within one function and use that variable in another function, but for some reason the variable comes out to be blank in the second function.

My thoughts

Either function 2 is executed first before function 1 (If this is the case, how do I command jQuery to start to execute a particular statement/function?)

Or

myvar global variable in function 1 is not set (if this is the case, what is the alternative to achieve this?)

var my_var;
//function 1
$(".div1").onhover(function(){
my_var="hello"
});
  
//function 2
$(".div1").onhover(function(){
 //i want to make use of my_var here, but it is blank
});
 
 //I want to use my_var it somewhere here too, but it doesnt work
      
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
katie
  • 2,921
  • 8
  • 34
  • 51
  • Global variable in JQuery: http://stackoverflow.com/questions/3352020/jquery-the-best-way-to-set-a-global-variable – JSuar Dec 01 '12 at 03:05
  • The problem is that `function 2` gets called first; but it's not clear what your code is supposed to do. – Ja͢ck Dec 01 '12 at 03:05
  • See this answer: http://stackoverflow.com/questions/290254/how-to-order-events-bound-with-jquery – Selosindis Dec 01 '12 at 03:15

1 Answers1

2

The correct function is .hover (more here); .onhover is not correct. The code below works the way you requested (live example).

HTML

<div id="TestID" class="div1">This is a test.</div>​

JavaScript

var my_var;
//function 1
$(".div1").hover(function(){
    my_var=$(this).attr('id'); 
});

//function 2
$(".div1").hover(function(){
    alert(my_var);
});​

Here are some additional helpful links on Global variables in JavaScript:

Community
  • 1
  • 1
JSuar
  • 21,056
  • 4
  • 39
  • 83
  • Thank you, when you use alert it works but when you use it within a statement it doesnt, onhover was a typo sorry. – katie Dec 01 '12 at 03:28
  • Here's an example using the variable in a statement: http://jsfiddle.net/EKdtj/2/. It still works. – JSuar Dec 01 '12 at 03:46
  • sorry i meant it doesnt work outside the function, how do i make it work? – katie Dec 01 '12 at 03:52
  • If the mouse hasn't hovered over a `div` thus firing the functions, then `my_var` won't be defined. You should be able to reference it anywhere without a problem. Here's an example: http://jsfiddle.net/EKdtj/4/ – JSuar Dec 01 '12 at 04:01
  • You'll have to post more code for with more context or modify one of the jsfiddles above replicating your issue. – JSuar Dec 01 '12 at 04:10
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/20445/discussion-between-jsuar-and-katie) – JSuar Dec 01 '12 at 13:23