views:

354

answers:

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  A: 

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.

karim79
note that he might not be using `button` tag.. his code is using a `button<x>` id.
Gaby
+1  A: 

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');
});
tvanfosson
ok got it thanks guyys
john morris
+1  A: 

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)

Brian Luft