0

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> 
1
  • 1
    Simple answer: Don't make it local. Commented Oct 9, 2014 at 15:03

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

yes, i try for 5 time to mark answer , but i must wait for 5 minute.
Of course the variable is not local anymore. It's impossible to access a local variable outside of the function.
0

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)

2 Comments

Yes, Answer edited. Personally I don't like to declare variables in the window/global scope but that's up to you
Why you don't like to declare variables ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.