Question

var myElements = document.getElementsByName('bb1');
    for (var i = 0; i < myElements.length; i++) {
        var curValue = myElements[i].getAttribute('innerId')
        myElements[i].addEventListener('mouseover', function () {
            alert('Hello i am : ' + curValue);
        }, false);
    }

when mouse over, every element, instead of showing a different value for curValue, a constant value (the last iteration value) is displayed.

what am i doing wrong here?

Was it helpful?

Solution

There is no different scope inside blocks like for in JavaScript, so when your mouseover event is triggered, it will alert the current variable value which was set in the last iteration.

You can just use this inside your callback function to get the attribute of the object which the event was triggered.

var myElements = document.getElementsByName('bb1');
for (var i = 0; i < myElements.length; i++) {
    myElements[i].addEventListener('mouseover', function () {
        alert('Hello i am : ' + this.getAttribute('innerId'));
    }, false);
}

OTHER TIPS

The general issue here is the closure in Javascript. This happens when using variable (in this case curValue) not defined within the callback function.

I recommend reading answers about JS closures here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top