3

This is probably really simple, and the answer is probably really obvious, but I'm drawing a blank here.

I have an array of HTML elements that I am binding the .hover() event to. I need to know what array index was used by the event.

So let's say element[7] is hovered over, how do I pass the number 7 to that function?

Here is what I am using:

for (i=0; i<statecount; i++) {
    $("#"+imagemap[i][0]).hover(function() {
        // Mouse enters HTML element

        alert(i); 

        // "i" returns 15, which makes sense because "i" 
        // has changed since this function was defined.
    });
}

4 Answers 4

2

Use a closure as a wrapper to save state.

for (i = 0; i < statecount; i+=1)
{
  (function(i){
    $('#'+imagemap[i][0]).hover(function () {
      alert(i);
    });
  }(i));
}
Sign up to request clarification or add additional context in comments.

4 Comments

This works, does this little trick have a name? I tried searching for jquery wrapper but it shows results for the wrap() function, etc. Thanks
@RadGH: JavaScript self-calling function I believe...or self-invoking function
"immediately invoked function expression": benalman.com/news/2010/11/…
Thanks for the comments, it's difficult to find things like this by just using google. Hehe
1

While this doesn't answer your question, you can get a handle to the object that was hovered over using this inside the function:

for (i=0; i<statecount; i++) {
    $("#"+imagemap[i][0]).hover(function() {
        alert(this);
    }
}

You might want to use $(this) if you want the JQuery object.

2 Comments

That's not what he asked for specifically, no, but it might be what he wants.
Thanks for the help, I knew about "this" already (heh). I considered looping through my array and comparing "this" to the element of the array, but couldn't get that to work - and if it did it would have been a very clunky way of doing it. Thanks though.
1

If you're using >= jQuery 1.6, $.proxy will curry parameters:

$.proxy(function(a, b, c) { ... }, this, 'argA', 'argB', 'argC');

so you could write it like this:

for (i=0; i<statecount; i++) {
    $("#"+imagemap[i][0]).hover($.proxy(function(index, event) {
        // Mouse enters HTML element

        alert(index); 
    }, this, i));
}

Note that this pushes the event the end of the argument list.

Comments

0

Be careful because this is easy to screw up:

var hoverer = function(i) {
  return function() {
         alert(i); 
  };
};

for (i=0; i<statecount; i++) {
        $("#"+imagemap[i][0]).hover(hoverer(i));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.