I am currently working on a website to learn some basic JavaScript stuff. I had the idea to build a litte gallery, with a diashow and some nice features.
However I came across some really strange problem. I've solved it already, but maybe anyone can explain whats goin on here. So I have an array with DIVs stored in it and want to add some mousehandler (in this example onmouseenter
and onmouseout
) so thats the code:
var buttonsdiv = [rightdiv, leftdiv];
for(var buttonsdivindex = 0; buttonsdivindex < buttonsdiv.length; buttonsdivindex++) {
buttonsdiv[buttonsdivindex].onmouseenter = function() {opacity(buttonsdiv[buttonsdivindex])};
buttonsdiv[buttonsdivindex].onmouseout = function() {opacity(buttonsdiv[buttonsdivindex])};
}
This doesn't work and I can't figure out why, because when I take the assignment out of the for loop, but still reference the array everything works fine. Even stranger, I've put the assignment in another function and put this function in the for loop and everything works quite fine.
var buttonsdiv = [rightdiv, leftdiv];
for(var buttonsdivindex = 0; buttonsdivindex < buttonsdiv.length; buttonsdivindex++) {
mousehandler(buttonsdiv[buttonsdivindex]);
}
function mousehandler(button) {
button.onmouseenter = function() {opacity(button)};
button.onmouseout = function() {opacity(button)};
}
Is there any explanation why the second one works and the first one doesn't?
Thanks, derdaist