Reputation: 717
This feels like a really basic question...that I cant find the answer for! Just a basic jQuery click function:
$('button.one').click(function () {
var selectorVal = 'one';
$('div#one').slideDown('slow');
$('div#two').slideUp('fast');
return selectorVal;
}
How do I retrieve and output selectorVal outside the function? Thanks so much!
Upvotes: 2
Views: 104
Reputation: 137450
You have two options:
Define variable outside the callback:
var selectorVal;
$('button.one').click(function (){
selectorVal = 'one';
$('div#one').slideDown('slow');
$('div#two').slideUp('fast');
});
// somewhere here check for selectorVal value (if any)
(better) Use another callback:
var doSomethingWithSelectorVal = function(selectorVal){
// here do something with updated selectorVal value
};
$('button.one').click(function (){
selectorVal = 'one';
$('div#one').slideDown('slow');
$('div#two').slideUp('fast');
doSomethingWithSelectorVal(selectorVal);
});
As I mentioned above, the second option is the better option, as using callback in this case is best suited.
Upvotes: 1
Reputation: 43
You can use window. Something like
$('button.one').click(function () {
window["var2"]="somedata";
}
After that, you will have access to the variable via the window but also on the global scope.
You can write alert(var2)
outside of the function and it will work.
Upvotes: 0
Reputation: 12890
Should make selectorVal a global variable like this; no need to return anything with that function:
var selectorVal = '';
$('button.one').click(function(){
selectorVal = 'one';
$('div#one').slideDown('slow');
$('div#two').slideUp('fast');
}
Upvotes: 1
Reputation: 2631
depends on when you want access it For example, if you sure that you access it after click function was executed, you can use such technique:
var outer_variable=null;
$('button.one').click(function () {
var selectorVal = 'one';
$('div#one').slideDown('slow');
$('div#two').slideUp('fast');
outer_variable=selectorVal;
return True;
}
Upvotes: 0
Reputation: 37711
Can you make a global variable outside of the function and then just add a value to it inside the function (no need to return anything then)?
Upvotes: 0