Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery loop hover button

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?

like image 702
john morris Avatar asked May 21 '26 21:05

john morris


2 Answers

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.

like image 73
karim79 Avatar answered May 24 '26 12:05

karim79


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');
});
like image 37
tvanfosson Avatar answered May 24 '26 11:05

tvanfosson