1

Well hello,

here is my problem. I have this Javascript and my variable called " position " doesn't keep the assigned values when I enter the

under[i].addEventListener("click", function(){

            alert(position.y + "  " + position.x);

            score[i].setAttribute("style","-webkit-transform: translateY(-" + position.y + "px); -webkit-transition: .5s ease-in-out .01s;");

            under[i].classList.add("popout");
            score[i].classList.add("popScore");

            under[i].classList.remove("underlayer_score");
            score[i].classList.remove("scores_teams");

        });

It is weird because when I check before or after this eventlistener the values are still assigned in that variable. I'm still a beginner in Javascript so, sorry if my explanation is not that clear.

Thank you for your help.

Here is the Javascript:

<script>

    var under = new Array(10);
        score = new Array(10);

    var position = 0;

    for(var i = 0; i <= 2; i++){

        under[i] = document.getElementsByClassName('underlayer_score')[i];
        score[i] = document.getElementsByClassName('scores_teams')[i];

    }

    function getPosition(element) {
        var xPosition = 0;
        var yPosition = 0;

        while(element) {
            xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
            yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
            element = element.offsetParent;
        }
        return { x: xPosition, y: yPosition };
    }


    for(var i = 0; i <= 2; i++){

        position = getPosition(score[i]);

        under[i].addEventListener("click", function(){

            alert(position.y + "  " + position.x);

            score[i].setAttribute("style","-webkit-transform: translateY(-" + position.y + "px); -webkit-transition: .5s ease-in-out .01s;");

            under[i].classList.add("popout");
            score[i].classList.add("popScore");

            under[i].classList.remove("underlayer_score");
            score[i].classList.remove("scores_teams");

        });

        alert(position.y);

        position.x = 0;
        position.y = 0;

    }

</script>
MightyPork
  • 18,270
  • 10
  • 79
  • 133
Igor Derval
  • 31
  • 1
  • 3
  • 1
    you need to wrap your event listener handler within a closure – epoch Jan 03 '15 at 19:05
  • What are you expecting to happen? – Etheryte Jan 03 '15 at 19:05
  • You set `position.y` to `0` after the `alert`, thats why `position.y` is `0` in the event handler. `position` is the same object for all of handlers. The same with with `i` which will be `3` for all handlers. – t.niese Jan 03 '15 at 19:07

1 Answers1

1

Maybe you should try to check what's insIde window.position? Could it be that position is not global?

vasilevich
  • 717
  • 9
  • 30