1

I want to apply mouse events for 114 divs. There are lots of condition for one div. I wrote for one div but there are about 900 lines. If I want to do that for 114 divs it will be really difficult and also boring. I tried examples below but didn't work.

var abc= new Array();
abc[0] = ".ABC";
abc[1] = ".DEF";

$(abc).mouseenter(function() {
    Some code
});

or

for (var a=0;a<114;a++) {
   $(abc[a]).mouseenter(function() {
      Some code
   });
}

or

while (var a=0;a<114;a++) {
    $(abc[a]).mouseenter(function() {
       Some code
    });
}

2 Answers 2

1

There is no need to define every events one by one. Give all of divs a class and select by the class name:

jsFiddle Demo

HTML

<div class="mydivs"></div>
<div class="mydivs"></div>
<div class="mydivs"></div>
....

jQuery

$('.mydivs').mouseenter(function() {
    // grab current div by $(this)
});
Sign up to request clarification or add additional context in comments.

2 Comments

are you sure you want to define 114 times the same function instead of refer always to the same
@Siamak.A.M Oh. I've been working all day. I couldn't think that. :) Thanks.
0

The better solution is probably to just put a common class on all the elements that you want the same event handler on, or (if you show us your HTML), you can perhaps use a single delegated event handler. But, if you insist on setting up separate event handlers for every item in the array, you can do this:

$(abc.join(", ")).mouseenter(function() {
    // you can access whatever object triggered the event
    // with the value in this
});

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.