One of the worst aspects of javascript is implied global scope. You could make your variable global just by dropping the var
keyword:
$('.bar1').animate({'height':'10' + "%"},1500, function() {
bar1_height = $(".bar1").height() * 0.5;
});
But this is considered very bad practice. For example:
var getAddress = function(street, city, country) {
location = street + ', ' + city + ', ' + country;
return location;
}
getAddress('Holborn', 'London', 'England');
Can you spot the horrendous bug? jsFiddle.
You should really declare your variable in the narrowest scope possible, otherwise you'll end up with a confusing mess of global variables. If you need a variable both inside and outside a function, you should simply declare it in the outer scope (as the other answers have said):
(function () {
var bar1_height;
$('.bar1').animate({'height':'10' + "%"},1500, function() {
// Use variable from outer scope
bar1_height = $(".bar1").height() * 0.5;
});
// Variable still has its value here
alert(bar1_height);
})();
(The mysterious outer function here is to prevent the variable from being truly global.)
I found this blog post very useful in understanding best practices regarding variable scope.