Reputation: 2951
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
Upvotes: 1
Views: 271
Reputation: 21091
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:
Upvotes: 2