JQuery hover button

ok I have 6 buttons, I'm trying to use a jquery listener, when you hover over one of the 6 buttons, it changes the class. im using a for loop for 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 identifier of "buttonx" (x is a number)

help?

+3
source share
3 answers

You do not need to use a loop. Just use the startWith attribute on the id selector. You can also change the way classes are applied / deleted to make sure that no class has a normal and a hover.

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

. "normal" :

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

'button.normal' "normal", , hover .

+2

Please note that karim79 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)

+1
source

Source: https://habr.com/ru/post/1736538/


All Articles