0

If you can't tell by my other questions, I'm a self-taught newb. I'm trying to consolidate some of my js code. I have 2 divs, with class a0 and a1. I'd like to attach a mouseenter event to each (same event).

Here's my fiddle, which is (hopefully) self-explanatory. .a0 and .a1 are my original code and .f0 and .f1 represents my (failed) attempt to consolidate. Why can't I do a "for" loop (or, if I can, why do I always end up w/ value of "2" for i?)?

(If there's a way I can do it in jquery, that's fine)

See above fiddle for full demo:

$(".a0").on("mouseenter",function(){
        $(this).html("value: 0");
});
$(".a1").on("mouseenter",function(){
        $(this).html("value: 1");
});

/* my failed attempt to consolidate the above code */
for (var i=0; i<2; i++){ 
    $(".f"+i).on("mouseenter",function(){
        $(this).html("value: "+ i);
    });
}
user_78361084
  • 3,538
  • 22
  • 85
  • 147
  • 4
    One of the best tips for a "newbie": Learn to give variables, functions, classes etc. *meaningful* names. – Ingo Bürk Mar 23 '13 at 19:19

2 Answers2

3

Quick & Dirty

$(".a0, .a1").on("mouseenter",function(){
  $(this).html("value: " + ($(this).hasClass('a0') ? 0 : 1));
});

More elegant

To resolve your question in a more elegant way, let's first understand why your code does not work.

You are defining two callbacks that will read into the value of i.

However, i will be already set to 2 when your mouse will enter the element.

You can use a closure to prevent this :

for (var i=0; i<2; i++){ 
  (function(j) {
    $(".f"+i).on("mouseenter",function(){
      $(this).html("value: "+ j);
    });
  })(i);
}

In this case, the value of i is captured into j and won't be changed when the callback is called.

Here is a Working fiddle

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
1

The problem is that i is a reference, and by the time your handler is called it is === 2 The following works for me.

var assignME = function (i) {
    $(".f"+i).on("mouseenter",function(){
        $(this).html("value: "+ i);
    });
};

for (var i=0; i<2; i++){
    assignME(i);
}
njwags
  • 1,107
  • 11
  • 22