MooTools/JavaScript variable scope

Posted by 827 on Stack Overflow See other posts from Stack Overflow or by 827
Published on 2010-06-13T02:20:19Z Indexed on 2010/06/13 2:22 UTC
Read the original article Hit count: 433

I am trying to make each number displayed clickable. "1" should alert() 80, "2" should produce 60, etc.

However, when the alert(adjust) is called, it only shows 0, not the correct numbers. However, if the commented out alert(adjust) is uncommented, it produces the correct number on page load, but not on clicking.

I was wondering why the code inside addEvents cannot access the previously defined variable adjust.

<html>
<head>
<script type="text/javascript" charset="utf-8" src="mootools.js"></script>
<script type="text/javascript" charset="utf-8">
    window.addEvent('domready', function() {

            var id_numbers = [1,2,3,4,5];

            for(var i = 0; i<id_numbers.length; i++) {
                var adjust = (20 * (5 - id_numbers[i]));
                // alert(adjust);
                $('i_' + id_numbers[i]).addEvents({
                    'click': function() {
                        alert(adjust);
                    }
                });
            }

    });
</script>
</head>
<body>

<div id="i_1">1</div>
<div id="i_2">2</div>
<div id="i_3">3</div>
<div id="i_4">4</div>
<div id="i_5">5</div>

</body>
</html>

Thanks.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about variable