0
for (var i = 1; i <= 3; i++)
{
    var tmpDiv = '#difdiv' + i;
    var tmpButton = '#difButton' + i;
    $(tmpDiv).css({
        position: "absolute",
        left: 0,
        top: $('#map').position().top - 16
    });
    $(tmpDiv).css('z-index', 3000);
    $(tmpDiv).css('width', '100%');

    $(tmpButton).hover(
        function () {
            $(tmpDiv).fadeIn(200);
        }, function () {
            $(tmpDiv).fadeOut(200);
        }
    );
}

I use this loop to add a hover dif to a variable amount of buttons. When I use this code, every jQuery-Element gets the "'#difdiv' + i". And at the end every buttons fades the same difdiv in and out. In this case difdiv3. How can I access the value give it to the jQuery element instead of the variable?

Vlorian
  • 89
  • 10

1 Answers1

2

The problem is the variable reference. Easy way around it is to take what is inside the loop and stuff it into a function and call it.

function createButton(i) {
    var tmpDiv = '#difdiv' + i;
    var tmpButton = '#difButton' + i;
    $(tmpDiv).css({
        position: "absolute",
        left: 0,
        top: $('#map').position().top - 16
    });
    $(tmpDiv).css('z-index', 3000);
    $(tmpDiv).css('width', '100%');

    $(tmpButton).hover(
        function () {
            $(tmpDiv).stop().fadeIn(200);  //added stop
        }, function () {
            $(tmpDiv).stop().fadeOut(200); //added stop
        }
    );
}

for (var i = 1; i <= 3; i++) {
    createButton(i);
}
epascarello
  • 204,599
  • 20
  • 195
  • 236