3

ok i have 6 buttons, im trying to have a jquery listener for when you hover over one of the 6 buttons, it changes class. im using a for loop to do this, heres my code:

$(document).ready(function() {
for($i=1;$i<7;$i++) {
      $('#button'+i).hover(function() {
        $(this).addClass('hovering');
      }, function() {
        $(this).removeClass('normal');
      });
}  
});

each button has an id of "buttonx" ( the x being a number )

help?

2
  • It would help to see your HTML. There are several methods to achieve your desired effect, but there may be a very clear and concise way depending on your situation. Commented Mar 11, 2010 at 18:47
  • You must be a perl/php programmer. You don't need $ in front of the i variables :) Commented Mar 11, 2010 at 18:52

3 Answers 3

2

You don't need to loop over a bunch of generated IDs. You can simply give each of them the class 'normal' and:

$("button.normal").hover(function() {
    $(this).addClass("hovering");
}, function() {
    $(this).removeClass("hovering");
});

'button.normal' will return a collection of all buttons with the 'normal' class, so there's no need for a loop, the hover event will be applied to every element in the collection.

Sign up to request clarification or add additional context in comments.

1 Comment

note that he might not be using button tag.. his code is using a button<x> id.
1

You shouldn't need to use a loop. Just use the attribute startsWith selector on the id. Also you may want to change how you apply/remove the classes to make sure that no class has both normal and hovering.

$('[id^=button]').hover( function() {
     $('[id^=button]').removeClass('hovering');
     $(this).addClass('hovering').removeClass('normal');
},
function() {
     $(this).removeClass('hovering').addClass('normal');
});

Comments

1

Note that karim79's answer is a good way to go.

In your code, you are declaring the loop counter as '$i' but trying to reference 'i'. It should be $('#button'+$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.