nomwery geqoilu
nomwery geqoilu

Reputation: 109

How to access to local variable from outside the function?

How to access to local variable from outside the function ?

When pressed, it should alert distance_bottom value, but it's not working, how can I make it work?

http://jsfiddle.net/dyjb8r9w/11/

<script>
$(window).load(function(){
(function() {    
    var mY, distance_bottom,
        $distance_bottom = $('#distance_bottom span'),
        $element_bottom  = $('#element_bottom');

    function calculatedistance_bottom(elem , mouseY) {
        return Math.floor(Math.sqrt(Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
    }

    $(document).mousemove(function(e) {        
        mY = e.pageY;
        distance_bottom = calculatedistance_bottom($element_bottom , mY);
        $distance_bottom.text(distance_bottom);
    });
})();
});
</script>





<script>
function reply_click()
{    
    alert(distance_bottom);
}
</script> 

Upvotes: 0

Views: 78

Answers (2)

CanIHazCookieNow
CanIHazCookieNow

Reputation: 152

The way I see it you have two options, first one implies changing the function and the other one doesn't:

1- make that a global variable by not declaring it inside the function with var

2- Access the value on the HTML using javascript/jQuery.

Ex: alert($('#distance_bottom span').html());

(Example in jQuery for simplicity)

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You can make it global by prefixing it with window. and removing it from the variable declaration at the top. The below line did the trick

window.distance_bottom = calculatedistance_bottom($element_bottom , mY);

DEMO

Upvotes: 2

Related Questions